Java Code Examples for java.io.FileInputStream#close()

The following examples show how to use java.io.FileInputStream#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZipOutput.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
public void addFile(String path) throws IOException {
    FileInputStream fi = new FileInputStream(path);
    BufferedInputStream origin = new BufferedInputStream(fi, BUFFER_SIZE);
    ZipEntry entry = new ZipEntry(path.substring(path.lastIndexOf("/") + 1));

    outputZipStream.putNextEntry(entry);

    int count;
    while ((count = origin.read(buffer, 0, BUFFER_SIZE)) != -1) {
        outputZipStream.write(buffer, 0, count);
    }
    origin.close();
    fi.close();

    Log.d(TAG, "Added: " + path);
}
 
Example 2
Source File: StreamingDoubleMatrix2D.java    From MFL with Apache License 2.0 6 votes vote down vote up
private void writeData(Sink sink) throws IOException {
    if (getNumElements() == 0)
        return;

    if (sink.order() != ByteOrder.nativeOrder())
        throw new IOException("Expected sink to be in native order");

    for (int col = 0; col < getNumCols(); col++) {

        // Make sure all data is on disk
        columnSinks[col].close();

        // Map each file and push data to sink
        FileInputStream input = new FileInputStream(tmpFiles[col]);
        try {
            int numBytes = getNumRows() * SIZEOF_DOUBLE;
            sink.writeInputStream(input, numBytes);
        } finally {
            input.close();
        }

    }

}
 
Example 3
Source File: PackageDestroyUtil.java    From AndroidStudyDemo with GNU General Public License v2.0 6 votes vote down vote up
/**
 * apk包破坏
 *
 * @param arg1 目标apk地址
 * @param arg2 破坏后的apk地址
 */
public static void destory(String arg1, String arg2) {
    try {
        File file = new File(arg1);
        FileInputStream in = new FileInputStream(file);
        FileOutputStream out = new FileOutputStream(new File(arg2));
        int read = 0;
        long count = 0;
        long readLen = file.length() - 512;
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        while ((read = in.read()) != -1) {
            count++;
            out.write(read);
            if (count >= readLen) {
                buffer.write(read);
            }
        }
        byte[] b = buffer.toByteArray();
        out.write(b);
        in.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: RmiBootstrapTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses the password file to read the credentials.
 * Returns an ArrayList of arrays of 2 string:
 * {<subject>, <password>}.
 * If the password file does not exists, return an empty list.
 * (File not found = empty file).
 **/
private ArrayList readCredentials(String passwordFileName)
    throws IOException {
    final Properties pws = new Properties();
    final ArrayList  result = new ArrayList();
    final File f = new File(passwordFileName);
    if (!f.exists()) return result;
    FileInputStream fin = new FileInputStream(passwordFileName);
    try {pws.load(fin);}finally{fin.close();}
    for (Enumeration en=pws.propertyNames();en.hasMoreElements();) {
        final String[] cred = new String[2];
        cred[0]=(String)en.nextElement();
        cred[1]=pws.getProperty(cred[0]);
        result.add(cred);
    }
    return result;
}
 
Example 5
Source File: Base64Utils.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
/**
 *encode file to  base64 Code String
 * @param fileName file path
 * @return  * 
 * @throws Exception
 */

public static String fileToBase64(String fileName) throws Exception {
 File file = new File(fileName);;
 FileInputStream inputFile = new FileInputStream(file);
 byte[] buffer = new byte[(int) file.length()];
 inputFile.read(buffer);
 inputFile.close();
 return encodeBase64(buffer);

}
 
Example 6
Source File: ZoneInfoFile.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads the specified file under &lt;java.home&gt;/lib/zi into a buffer.
 * @return the buffer, or null if any I/O error occurred.
 */
private static byte[] readZoneInfoFile(final String fileName) {
    if (fileName.indexOf("..") >= 0) {
        return null;
    }
    byte[] buffer = null;
    File file = new File(ziDir, fileName);
    try {
        int filesize = (int)file.length();
        if (filesize > 0) {
            FileInputStream fis = new FileInputStream(file);
            buffer = new byte[filesize];
            try {
                if (fis.read(buffer) != filesize) {
                    throw new IOException("read error on " + fileName);
                }
            } finally {
                fis.close();
            }
        }
    } catch (Exception ex) {
        if (!(ex instanceof FileNotFoundException) || JAVAZM_FILE_NAME.equals(fileName)) {
            System.err.println("ZoneInfoOld: " + ex.getMessage());
        }
    }
    return buffer;
}
 
Example 7
Source File: DecryptingPartInputStream.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private static void verifyMac(MasterSecret masterSecret, File file) throws IOException {
  Mac             mac        = initializeMac(masterSecret.getMacKey());
  FileInputStream macStream  = new FileInputStream(file);
  InputStream     dataStream = new LimitedInputStream(new FileInputStream(file), file.length() - MAC_LENGTH);
  byte[]          theirMac   = new byte[MAC_LENGTH];

  if (macStream.skip(file.length() - MAC_LENGTH) != file.length() - MAC_LENGTH) {
    throw new IOException("Unable to seek");
  }

  readFully(macStream, theirMac);

  byte[] buffer = new byte[4096];
  int    read;

  while ((read = dataStream.read(buffer)) != -1) {
    mac.update(buffer, 0, read);
  }

  byte[] ourMac = mac.doFinal();

  if (!MessageDigest.isEqual(ourMac, theirMac)) {
    throw new IOException("Bad MAC");
  }

  macStream.close();
  dataStream.close();
}
 
Example 8
Source File: OauthClientTest.java    From maven-framework-project with MIT License 5 votes vote down vote up
private static KeyStore loadKeyStore(String filename, String password)
		throws Exception {
	KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
	File truststoreFile = new File(filename);
	FileInputStream trustStream = new FileInputStream(truststoreFile);
	trustStore.load(trustStream, password.toCharArray());
	trustStream.close();
	return trustStore;
}
 
Example 9
Source File: ReadUnsignedInt.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RIFFWriter writer = null;
    RIFFReader reader = null;
    File tempfile = File.createTempFile("test",".riff");
    try
    {
        writer = new RIFFWriter(tempfile, "TEST");
        RIFFWriter chunk = writer.writeChunk("TSCH");
        chunk.writeUnsignedInt(55377);
        writer.close();
        writer = null;
        FileInputStream fis = new FileInputStream(tempfile);
        reader = new RIFFReader(fis);
        assertEquals(reader.getFormat(), "RIFF");
        assertEquals(reader.getType(), "TEST");
        RIFFReader readchunk = reader.nextChunk();
        assertEquals(readchunk.getFormat(), "TSCH");
        assertEquals(reader.readUnsignedInt(), 55377L);
        fis.close();
        reader = null;


    }
    finally
    {
        if(writer != null)
            writer.close();
        if(reader != null)
            reader.close();

        if(tempfile.exists())
            if(!tempfile.delete())
                tempfile.deleteOnExit();
    }
}
 
Example 10
Source File: ZipVerifyUtil.java    From VirtualAPK with Apache License 2.0 5 votes vote down vote up
public static Certificate getCertificate(String certificatePath) throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(certificatePath);
    Certificate certificate = certificateFactory.generateCertificate(in);
    in.close();
    return certificate;
}
 
Example 11
Source File: Solution.java    From JavaExercises with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    FileInputStream file = new FileInputStream(reader.readLine());
    int max = 0;
    while (file.available() > 0) {
        int b = file.read();
        if (b > max)
            max = b;
    }
    file.close();
    System.out.println(max);
}
 
Example 12
Source File: SBOLUtility.java    From iBioSim with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve property file for synthesis view 
 * 
 * @param synthFilePath - Path to property file for synthesis view
 * @param separator - a separator to handle directory
 * @param frame - the UI frame that this synthesis view is operating on.
 * @return The property file for synthesis view
 * @throws IOException - Synthesis specification property is missing.
 */
public Properties loadSBOLSynthesisProperties(String synthFilePath, String separator, JFrame frame) throws IOException {
	Properties synthProps = new Properties();
	for (String synthFileID : new File(synthFilePath).list())
	{
		if (synthFileID.endsWith(GlobalConstants.SBOL_SYNTH_PROPERTIES_EXTENSION)) 
		{
				FileInputStream propStreamIn = new FileInputStream(new File(synthFilePath + separator + synthFileID));
				synthProps.load(propStreamIn);
				propStreamIn.close();
				return synthProps;
		}	
	}
	return synthProps;
}
 
Example 13
Source File: WordCountUtil.java    From WordCount with GNU General Public License v2.0 5 votes vote down vote up
public static String readAllFromFile(File f) throws IOException {
    FileInputStream fis = new FileInputStream(f);
    byte[] buf = new byte[2048];
    int read;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((read = fis.read(buf)) != -1) {
        bos.write(buf, 0, read);
    }
    fis.close();
    return bos.toString();

}
 
Example 14
Source File: BaseApp.java    From ion-java with Apache License 2.0 5 votes vote down vote up
protected static byte[] loadAsByteArray(File file)
    throws FileNotFoundException, IOException
{
    long len = file.length();
    if (len < 0 || len > Integer.MAX_VALUE)
    {
        throw new IllegalArgumentException("File too long: " + file);
    }

    byte[] buffer = new byte[(int) len];

    FileInputStream in = new FileInputStream(file);
    try
    {
        int readBytesCount = in.read(buffer);
        if (readBytesCount != len || in.read() != -1)
        {
            System.err.println("Read the wrong number of bytes from "
                                   + file);
            return null;
        }
    }
    finally
    {
        in.close();
    }

    return buffer;
}
 
Example 15
Source File: GetSize.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RIFFWriter writer = null;
    RIFFReader reader = null;
    File tempfile = File.createTempFile("test",".riff");
    try
    {
        writer = new RIFFWriter(tempfile, "TEST");
        RIFFWriter chunk = writer.writeChunk("TSCH");
        chunk.writeByte(10);
        writer.close();
        writer = null;
        FileInputStream fis = new FileInputStream(tempfile);
        reader = new RIFFReader(fis);
        RIFFReader readchunk = reader.nextChunk();
        assertEquals(readchunk.getSize(), (long)readchunk.available());
        readchunk.readByte();
        fis.close();
        reader = null;


    }
    finally
    {
        if(writer != null)
            writer.close();
        if(reader != null)
            reader.close();

        if(tempfile.exists())
            if(!tempfile.delete())
                tempfile.deleteOnExit();
    }
}
 
Example 16
Source File: ReadUnsignedByte.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RIFFWriter writer = null;
    RIFFReader reader = null;
    File tempfile = File.createTempFile("test",".riff");
    try
    {
        writer = new RIFFWriter(tempfile, "TEST");
        RIFFWriter chunk = writer.writeChunk("TSCH");
        chunk.writeUnsignedByte(77);
        writer.close();
        writer = null;
        FileInputStream fis = new FileInputStream(tempfile);
        reader = new RIFFReader(fis);
        assertEquals(reader.getFormat(), "RIFF");
        assertEquals(reader.getType(), "TEST");
        RIFFReader readchunk = reader.nextChunk();
        assertEquals(readchunk.getFormat(), "TSCH");
        assertEquals(reader.readUnsignedByte(), 77);
        fis.close();
        reader = null;


    }
    finally
    {
        if(writer != null)
            writer.close();
        if(reader != null)
            reader.close();

        if(tempfile.exists())
            if(!tempfile.delete())
                tempfile.deleteOnExit();
    }
}
 
Example 17
Source File: StackLogDecoder.java    From unidbg with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    File stackLog = new File("target/stack-logs.78490.2000.unidbg.zcmkle.index");
    FileInputStream inputStream = new FileInputStream(stackLog);
    FileChannel channel = inputStream.getChannel();
    MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, stackLog.length());
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    int i = 0;
    while (buffer.remaining() >= 16) {
        long size = buffer.getInt() & 0xffffffffL;
        long addr = (buffer.getInt() & 0xffffffffL) ^ 0x00005555;
        long offset_and_flags_l = buffer.getInt() & 0xffffffffL;
        long offset_and_flags_h = buffer.getInt() & 0xffffffffL;
        int flag = (int) ((offset_and_flags_h & 0xff000000) >> 24);
        long stackId = ((offset_and_flags_h & 0x00ffffff) << 32) | offset_and_flags_l;
        String action = "OTHER";
        boolean isFree = false;
        switch (flag) {
            case MALLOC_LOG_TYPE_ALLOCATE:
                action = "ALLOC";
                isFree = false;
                break;
            case MALLOC_LOG_TYPE_DEALLOCATE:
                action = "FREE ";
                isFree = true;
                break;
            case stack_logging_type_vm_allocate:
                action = "MMAP ";
                isFree = false;
                break;
            case stack_logging_type_vm_deallocate:
                action = "UNMAP";
                isFree = true;
                break;
            default:
                if ((flag & stack_logging_type_mapped_file_or_shared_mem) != 0 && (flag & stack_logging_type_vm_allocate) != 0) {
                    action = "MMAPF";
                    isFree = false;
                    break;
                }

                System.err.println(flag);
                break;
        }
        String msg = String.format("[%08d]: %s, stackId=0x%014x, address=0x%08x, size=0x%x", i++, action, stackId, addr, size);
        if (isFree) {
            System.err.println(msg);
        } else {
            System.out.println(msg);
        }
    }
    channel.close();
    inputStream.close();
}
 
Example 18
Source File: NetworkUtil.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static HttpResponse postFile(
        String targetURL,
        String fileName,
        File file,
        String fileMime,
        String username,
        String password,
        boolean readErrorResponseBody)
        throws IOException
{
    final String lineEnd = "\r\n";
    final String twoHyphens = "--";
    final String boundary = "**nextgis**";

    //------------------ CLIENT REQUEST
    FileInputStream fileInputStream = new FileInputStream(file);
    // open a URL connection to the Servlet

    HttpURLConnection conn = getHttpConnection(HTTP_POST, targetURL, username, password);
    if (null == conn) {
        if (Constants.DEBUG_MODE)
            Log.d(TAG, "Error get connection object: " + targetURL);
        return new HttpResponse(ERROR_CONNECT_FAILED);
    }
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    // Allow Outputs
    conn.setDoOutput(true);

    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes(
            "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" +
            lineEnd);

    if (!TextUtils.isEmpty(fileMime)) {
        dos.writeBytes("Content-Type: " + fileMime + lineEnd);
    }

    dos.writeBytes(lineEnd);

    byte[] buffer = new byte[Constants.IO_BUFFER_SIZE];
    FileUtil.copyStream(fileInputStream, dos, buffer, Constants.IO_BUFFER_SIZE);

    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    fileInputStream.close();
    dos.flush();
    dos.close();

    return getHttpResponse(conn, readErrorResponseBody);
}
 
Example 19
Source File: FileManager.java    From letv with Apache License 2.0 4 votes vote down vote up
public BufferedOutputStream makeOutputStream(String str) {
    OutputStream openFileOutput;
    Exception e;
    BufferedOutputStream bufferedOutputStream = null;
    try {
        int available;
        byte[] bArr = new byte[1024];
        try {
            FileInputStream fileInputStream = new FileInputStream(str);
            openFileOutput = this.bн043D043Dн043D043D.openFileOutput(new String(getUniqueFileName(str) + HAPTIC_STORAGE_FILENAME), 0);
            try {
                for (available = fileInputStream.available(); available > 0; available = fileInputStream.available()) {
                    openFileOutput.write(bArr, 0, fileInputStream.read(bArr));
                }
                fileInputStream.close();
            } catch (Exception e2) {
                e = e2;
                try {
                    e.printStackTrace();
                    if (openFileOutput != null) {
                        bufferedOutputStream = new BufferedOutputStream(openFileOutput);
                    }
                    available = b0425Х042504250425Х;
                    switch ((available * (b04250425042504250425Х + available)) % bХХХХХ0425) {
                        case 0:
                            break;
                        default:
                            b0425Х042504250425Х = b0425ХХХХ0425();
                            bХ0425042504250425Х = 34;
                            break;
                    }
                    return bufferedOutputStream;
                } catch (Exception e3) {
                    throw e3;
                }
            }
        } catch (Exception e4) {
            e = e4;
            openFileOutput = null;
            e.printStackTrace();
            if (openFileOutput != null) {
                bufferedOutputStream = new BufferedOutputStream(openFileOutput);
            }
            available = b0425Х042504250425Х;
            switch ((available * (b04250425042504250425Х + available)) % bХХХХХ0425) {
                case 0:
                    break;
                default:
                    b0425Х042504250425Х = b0425ХХХХ0425();
                    bХ0425042504250425Х = 34;
                    break;
            }
            return bufferedOutputStream;
        }
        if (openFileOutput != null) {
            bufferedOutputStream = new BufferedOutputStream(openFileOutput);
        }
        available = b0425Х042504250425Х;
        switch ((available * (b04250425042504250425Х + available)) % bХХХХХ0425) {
            case 0:
                break;
            default:
                b0425Х042504250425Х = b0425ХХХХ0425();
                bХ0425042504250425Х = 34;
                break;
        }
        return bufferedOutputStream;
    } catch (Exception e32) {
        throw e32;
    }
}
 
Example 20
Source File: UddiDigitalSignatureFile.java    From juddi with Apache License 2.0 4 votes vote down vote up
public void fire(String fileIn, String fileOut, UddiType type) {
        try {
                System.out.println("WARN - All previous signatures will be removed!");
                if (fileIn == null || fileOut == null || type == null) {
                        System.out.print("Input file: ");
                        fileIn = System.console().readLine();
                        System.out.print("Out file: ");
                        fileOut = System.console().readLine();
                        System.out.println();
                        for (int i = 0; i < UddiType.values().length; i++) {
                                System.out.println("[" + i + "] " + UddiType.values()[i].toString());
                        }
                        System.out.print("UDDI Type: ");
                        String t = System.console().readLine();
                        type = UddiType.values()[Integer.parseInt(t)];
                }

                DigSigUtil ds = null;

                //option 1), set everything manually
                ds = new DigSigUtil();
                ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE, "keystore.jks");
                ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE, "JKS");
                ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD, "Test");
                ds.put(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS, "Test");
                ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true");

                ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SERIAL, "true");
                ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN, "true");
                ds.put(DigSigUtil.TRUSTSTORE_FILE, "truststore.jks");
                ds.put(DigSigUtil.TRUSTSTORE_FILETYPE, "JKS");
                ds.put(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, "Test");

                FileInputStream fis = new FileInputStream(fileIn);
                Class expectedType = null;
                switch (type) {
                        case Binding:
                                expectedType = BindingTemplate.class;
                                break;
                        case Business:
                                expectedType = BusinessEntity.class;
                                break;
                        case PublisherAssertion:
                                expectedType = PublisherAssertion.class;
                                break;
                        case Service:
                                expectedType = BusinessService.class;
                                break;
                        case TModel:
                                expectedType = TModel.class;
                                break;
                }
                Object be = XmlUtils.unmarshal(fis, expectedType);
                fis.close();
                fis = null;

                switch (type) {
                        case Binding:
                                ((BindingTemplate) be).getSignature().clear();
                                break;
                        case Business:
                                ((BusinessEntity) be).getSignature().clear();
                                break;
                        case PublisherAssertion:
                                ((PublisherAssertion) be).getSignature().clear();
                                break;
                        case Service:
                                ((BusinessService) be).getSignature().clear();
                                break;
                        case TModel:
                                ((TModel) be).getSignature().clear();
                                break;
                }

                System.out.println("signing");
                Object signUDDI_JAXBObject = ds.signUddiEntity(be);
                System.out.println("signed");
                DigSigUtil.JAXB_ToStdOut(signUDDI_JAXBObject);

                System.out.println("verifing");
                AtomicReference<String> msg = new AtomicReference<String>();
                boolean verifySigned_UDDI_JAXB_Object = ds.verifySignedUddiEntity(signUDDI_JAXBObject, msg);
                if (verifySigned_UDDI_JAXB_Object) {
                        System.out.println("signature validation passed (expected)");
                        FileOutputStream fos = new FileOutputStream(fileOut);
                        JAXB.marshal(signUDDI_JAXBObject, fos);
                        fos.close();
                } else {
                        System.out.println("signature validation failed (not expected)");
                }
                System.out.println(msg.get());

        } catch (Exception e) {
                e.printStackTrace();
        }
}