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

The following are Jave code examples for showing how to use close() of the java.io.FileInputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: FileOperation   File: NIOMerge.java   View Source Code Vote up 6 votes
public static void fileCombination(File file, String targetFile) throws Exception {
	outFile = new File(targetFile);	
	outDest = new RandomAccessFile(outFile,"rw");     
	childReader = new BufferedReader(new FileReader(file));
	long temp = 0;
	while ((name = childReader.readLine()) != null) {
		cFile = new File(name);
		long size = cFile.length();
		fileReader = new FileInputStream(cFile);	
		read = fileReader.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, size); 
		out = outDest.getChannel().map(FileChannel.MapMode.READ_WRITE, temp, size); 	
		temp += size; 
		for (long j = 0; j < size; j++) {  
	         byte b = read.get();    
	         out.put(b);               
	    }  	
	    fileReader.close();
		UnMap.unmap(read);
		UnMap.unmap(out);
	}			
	outDest.close();      
	childReader.close();
}
 
Example 2
Project: DIA-Umpire-Maven   File: DIA_Setting.java   View Source Code Vote up 6 votes
public static DIA_Setting ReadDIASettingSerialization(String filepath) {
    if (!new File(FilenameUtils.getFullPath(filepath) + FilenameUtils.getBaseName(filepath) + "_diasetting.ser").exists()) {
        return null;
    }
    try {
        Logger.getRootLogger().debug("Reading DIA setting from file:" + FilenameUtils.getFullPath(filepath) + FilenameUtils.getBaseName(filepath) + "_diasetting.ser...");

        FileInputStream fileIn = new FileInputStream(FilenameUtils.getFullPath(filepath) + FilenameUtils.getBaseName(filepath) + "_diasetting.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        DIA_Setting setting = (DIA_Setting) in.readObject();
        in.close();
        fileIn.close();
        return setting;

    } catch (Exception ex) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
        return null;
    }
}
 
Example 3
Project: Paper-Melody   File: PlayListenActivity.java   View Source Code Vote up 6 votes
private void copyToAndroidData(String sourcePath, String destPath) {
    Log.i("nib", "dest: " + destPath + "\n" + "source:" + sourcePath);
    try {
        FileInputStream inputStream = new FileInputStream(new File(sourcePath));
        FileOutputStream outputStream = new FileOutputStream(new File(destPath));
        byte bt[] = new byte[1024];
        int c;
        while ((c = inputStream.read(bt)) > 0) {
            outputStream.write(bt, 0, c);
        }
        inputStream.close();
        outputStream.close();
        ToastUtil.showShort(R.string.save_success);
        btnSaveToLocal.setClickable(false);
        Log.i("nib", "复制完成");
    } catch (Exception e) {
        Log.i("nib", e.toString());
    }
}
 
Example 4
Project: JAddOn   File: JAppZip.java   View Source Code Vote up 6 votes
/**
 * Zip it
 */
public void zipIt(){
    byte[] buffer = new byte[1024];
    try{
        FileOutputStream fos = new FileOutputStream(OUTPUT_ZIP_FILE);
        ZipOutputStream zos = new ZipOutputStream(fos);
        //System.out.println("Output to Zip : " + zipFile);
        for(String file : this.fileList){
            //System.out.println("File Added : " + file);
            ZipEntry ze= new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(SOURCE_FOLDER.getAbsolutePath() + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
       }
       zos.closeEntry();
       zos.close();
       //System.out.println("Done");
    } catch (IOException ex) {
        ex.printStackTrace();   
    }
}
 
Example 5
Project: mobiletailchanger   File: MainActivity.java   View Source Code Vote up 6 votes
String fileTxtRead(String fileName)
{  
	String res="";
       try
	{
		File file = new File(fileName);  
		FileInputStream fis = new FileInputStream(file);  
		int length = fis.available(); 
		byte [] buffer = new byte[length]; 
		fis.read(buffer);     
		res = EncodingUtils.getString(buffer, "UTF-8"); 
		fis.close();     
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}  
	return res;
}
 
Example 6
Project: parabuild-ci   File: SqlFile.java   View Source Code Vote up 6 votes
/**
 * Binary file load
 */
static public byte[] loadBinary(File binFile) throws IOException {
    byte[]                xferBuffer = new byte[10240];
    ByteArrayOutputStream baos       = new ByteArrayOutputStream();
    int                   i;
    FileInputStream       fis        = new FileInputStream(binFile);

    try {
        while ((i = fis.read(xferBuffer)) > 0) {
            baos.write(xferBuffer, 0, i);
        }
    } finally {
        fis.close();
    }

    byte[] ba = baos.toByteArray();

    return ba;
}
 
Example 7
Project: incubator-netbeans   File: GenerateJNLPApplicationTest.java   View Source Code Vote up 6 votes
private void copyFiles(File from, File to) throws IOException {
    LOG.fine("Copy " + from + " to " + to);
    if (from.isDirectory()) {
        to.mkdirs();
        for (File f : from.listFiles()) {
            copyFiles(f, new File(to, f.getName()));
        }
    } else {
        byte[] arr = new byte[4096];
        FileInputStream is = new FileInputStream(from);
        FileOutputStream os = new FileOutputStream(to);
        for (;;) {
            int r = is.read(arr);
            if (r == -1) {
                break;
            }
            os.write(arr, 0, r);
        }
        is.close();
        os.close();
    }
    
}
 
Example 8
Project: hadoop   File: TestSlive.java   View Source Code Vote up 6 votes
@Test
public void testDataWriting() throws Exception {
  long byteAm = 100;
  File fn = getTestFile();
  DataWriter writer = new DataWriter(rnd);
  FileOutputStream fs = new FileOutputStream(fn);
  GenerateOutput ostat = writer.writeSegment(byteAm, fs);
  LOG.info(ostat);
  fs.close();
  assertTrue(ostat.getBytesWritten() == byteAm);
  DataVerifier vf = new DataVerifier();
  FileInputStream fin = new FileInputStream(fn);
  VerifyOutput vfout = vf.verifyFile(byteAm, new DataInputStream(fin));
  LOG.info(vfout);
  fin.close();
  assertEquals(vfout.getBytesRead(), byteAm);
  assertTrue(vfout.getChunksDifferent() == 0);
}
 
Example 9
Project: nanocheeze   File: Torrent2.java   View Source Code Vote up 6 votes
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
        throws Exception {
    File folder = new File(srcFile);
    if (folder.isDirectory()) {
        addFolderToZip(path, srcFile, zip);
    } else {

        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        in.close();

    }
}
 
Example 10
Project: Loyalty   File: CacheManager.java   View Source Code Vote up 5 votes
public Bitmap restoreFromCache(Card card, Cache cache) throws IOException {
    String fileName = cache.getCacheLocation(getFileName(card));
    FileInputStream in = context.openFileInput(fileName);
    Bitmap out = BitmapFactory.decodeStream(in);
    in.close();
    return out;
}
 
Example 11
Project: encdroidMC   File: EncFSConfigParser.java   View Source Code Vote up 5 votes
/**
 * Parse the given configuration file
 * 
 * @param configFile
 *            EncFS volume configuration file.
 * @return An EncFSConfig object containing the configuration data
 *         interpreted from the given file.
 */
public static EncFSConfig parseFile(File configFile)
		throws ParserConfigurationException, SAXException, IOException,
		EncFSInvalidConfigException, EncFSUnsupportedException {
	FileInputStream inputStream = new FileInputStream(configFile);
	try {
		return parseFile(inputStream);
	} finally {
		inputStream.close();
	}

}
 
Example 12
Project: acs-demos   File: Player.java   View Source Code Vote up 5 votes
public static Player load(String playerName) throws IOException, ClassNotFoundException {
	String filename = playerName + ".player";
	Player player = null;
       FileInputStream fileIn = new FileInputStream(filename);
       ObjectInputStream in = new ObjectInputStream(fileIn);
       player = (Player) in.readObject();
       in.close();
       fileIn.close();
       logger.info("Loaded Player definition file from `" + filename + "`");
       return player;
}
 
Example 13
Project: MARF-for-Android   File: WaveFileReader.java   View Source Code Vote up 5 votes
/**
 * Obtains the audio file format of the File provided.  The File must
 * point to valid audio file data.
 *
 * @param file the File from which file format information should be
 *             extracted
 * @return an <code>AudioFileFormat</code> object describing the audio file format
 * @throws UnsupportedAudioFileException if the File does not point to valid audio
 *                                       file data recognized by the system
 * @throws IOException                   if an I/O exception occurs
 */
public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException {
    AudioFileFormat fileFormat = null;
    FileInputStream fis = new FileInputStream(file);       // throws IOException
    // part of fix for 4325421
    try {
        fileFormat = getFMT(fis, false);
    } finally {
        fis.close();
    }

    return fileFormat;
}
 
Example 14
Project: Hydrograph   File: FileStorageEditorContainer.java   View Source Code Vote up 5 votes
/**
 * Generate Container from xml,Setting FileStorageEditor Input into Ifile
 * @return Container
 * @throws IOException
 */
@Override
public Container getEditorInput() throws IOException {
	logger.debug("storeEditorInput - Setting FileStorageEditor Input into Ifile");
	Container con = null;
	File file = new File(fileStorageEditorInput.getToolTipText());
	FileInputStream fs = new FileInputStream(file);
	con = (Container) CanvasUtils.INSTANCE.fromXMLToObject(fs);
	this.eltGraphicalEditorInstance.setPartName(file.getName());
	fs.close();
	return con;
}
 
Example 15
Project: PaoMovie   File: CheapAMR.java   View Source Code Vote up 5 votes
public void WriteFile(File outputFile, int startFrame, int numFrames)
        throws java.io.IOException {
    outputFile.createNewFile();
    FileInputStream in = new FileInputStream(mInputFile);
    FileOutputStream out = new FileOutputStream(outputFile);

    byte[] header = new byte[6];
    header[0] = '#';
    header[1] = '!';
    header[2] = 'A';
    header[3] = 'M';
    header[4] = 'R';
    header[5] = '\n';
    out.write(header, 0, 6);

    int maxFrameLen = 0;
    for (int i = 0; i < numFrames; i++) {
        if (mFrameLens[startFrame + i] > maxFrameLen)
            maxFrameLen = mFrameLens[startFrame + i];
    }
    byte[] buffer = new byte[maxFrameLen];
    int pos = 0;
    for (int i = 0; i < numFrames; i++) {
        int skip = mFrameOffsets[startFrame + i] - pos;
        int len = mFrameLens[startFrame + i];
        if (skip < 0) {
            continue;
        }
        if (skip > 0) {
            in.skip(skip);
            pos += skip;
        }
        in.read(buffer, 0, len);
        out.write(buffer, 0, len);
        pos += len;
    }

    in.close();
    out.close();
}
 
Example 16
Project: PureMusic   File: LyricView.java   View Source Code Vote up 5 votes
public void setLyricFile(File file) {

        if (file == null || !file.exists()) {
            reset();
            return;
        } else if (file.getPath().equals(mCurrentLyricFilePath)) {
            return;
        } else {
            mCurrentLyricFilePath = file.getPath();
            reset();
        }
        try {

            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            UniversalDetector detector = new UniversalDetector(null);
            int nread;
            while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }

            detector.dataEnd();
            String encoding = detector.getDetectedCharset();
            if (encoding != null) {
                setLyricFile(file, encoding);
            } else {
                setLyricFile(file, "UTF-8");
            }
            detector.reset();
            fis.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 17
Project: ISO8583   File: ExcelReader.java   View Source Code Vote up 4 votes
public ExcelReader(String fileName, String sheetName) {

		int rowNumber = 0;
		int colNumber = 0;

		try {
			FileInputStream file = new FileInputStream(new File(fileName));
			XSSFWorkbook workbook = new XSSFWorkbook(file);
			XSSFSheet sheet;
			Iterator<Row> rowIterator;
			
			if (sheetName != null)
				sheet = workbook.getSheet(sheetName);
			else
				sheet = workbook.getSheetAt(0);
			
			Row row;
			Cell cell;
			Iterator<Cell> cellIterator;
			
			if (sheet != null) {
				rowIterator = sheet.iterator();
				
				while (rowIterator.hasNext()) {
					row = rowIterator.next();
					cellIterator = row.cellIterator();
					colNumber = 0;
					
					while (cellIterator.hasNext()) {
						cell = cellIterator.next();
						
						if (rowNumber == 0)
							celNum.put(cellVal(cell), colNumber);
						else
							celValues.put("["+ rowNumber +","+ colNumber +"]", cellVal(cell));
						
						colNumber++;
					}
					
					rowNumber++;
				}
			}
			
			rowCount = rowNumber - 1;
			file.close();
		}
		catch (Exception x) {
			x.printStackTrace();
		}
	}
 
Example 18
Project: hadoop   File: TestConcatenatedCompressedInput.java   View Source Code Vote up 4 votes
/**
 * Test using the raw Inflater codec for reading gzip files.
 */
@Test
public void testPrototypeInflaterGzip() throws IOException {
  CompressionCodec gzip = new GzipCodec();  // used only for file extension
  localFs.delete(workDir, true);            // localFs = FileSystem instance

  System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using " +
    "non-native/Java Inflater and manual gzip header/trailer parsing" +
    COLOR_NORMAL);

  // copy prebuilt (correct!) version of concat.gz to HDFS
  final String fn = "concat" + gzip.getDefaultExtension();
  Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
  Path fnHDFS  = new Path(workDir, fn);
  localFs.copyFromLocalFile(fnLocal, fnHDFS);

  final FileInputStream in = new FileInputStream(fnLocal.toString());
  assertEquals("concat bytes available", 148, in.available());

  // should wrap all of this header-reading stuff in a running-CRC wrapper
  // (did so in BuiltInGzipDecompressor; see below)

  byte[] compressedBuf = new byte[256];
  int numBytesRead = in.read(compressedBuf, 0, 10);
  assertEquals("header bytes read", 10, numBytesRead);
  assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
  assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
  assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

  byte flags = (byte)(compressedBuf[3] & 0xff);
  if ((flags & 0x04) != 0) {   // FEXTRA
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("XLEN bytes read", 2, numBytesRead);
    int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    in.skip(xlen);
  }
  if ((flags & 0x08) != 0) {   // FNAME
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading filename",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0x10) != 0) {   // FCOMMENT
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading comment",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0xe0) != 0) {   // reserved
    assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
  }
  if ((flags & 0x02) != 0) {   // FHCRC
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("CRC16 bytes read", 2, numBytesRead);
    int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
  }

  // ready to go!  next bytes should be start of deflated stream, suitable
  // for Inflater
  numBytesRead = in.read(compressedBuf);

  // Inflater docs refer to a "dummy byte":  no clue what that's about;
  // appears to work fine without one
  byte[] uncompressedBuf = new byte[256];
  Inflater inflater = new Inflater(true);

  inflater.setInput(compressedBuf, 0, numBytesRead);
  try {
    int numBytesUncompressed = inflater.inflate(uncompressedBuf);
    String outString =
      new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
    System.out.println("uncompressed data of first gzip member = [" +
                       outString + "]");
  } catch (java.util.zip.DataFormatException ex) {
    throw new IOException(ex.getMessage());
  }

  in.close();
}
 
Example 19
Project: boohee_v5.6   File: HttpUtils.java   View Source Code Vote up 4 votes
MyX509TrustManager() throws Exception {
    KeyStore instance;
    Throwable th;
    FileInputStream fileInputStream;
    try {
        instance = KeyStore.getInstance("JKS");
    } catch (Exception e) {
        instance = null;
    }
    TrustManager[] trustManagerArr = new TrustManager[0];
    if (instance != null) {
        try {
            InputStream fileInputStream2 = new FileInputStream("trustedCerts");
            try {
                instance.load(fileInputStream2, "passphrase".toCharArray());
                TrustManagerFactory instance2 = TrustManagerFactory.getInstance
                        ("SunX509", "SunJSSE");
                instance2.init(instance);
                TrustManager[] trustManagers = instance2.getTrustManagers();
                if (fileInputStream2 != null) {
                    fileInputStream2.close();
                }
            } catch (Throwable th2) {
                th = th2;
                InputStream inputStream = fileInputStream2;
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                throw th;
            }
        } catch (Throwable th3) {
            Throwable th4 = th3;
            fileInputStream = null;
            th = th4;
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            throw th;
        }
    }
    TrustManagerFactory instance3 = TrustManagerFactory.getInstance(TrustManagerFactory
            .getDefaultAlgorithm());
    instance3.init((KeyStore) null);
    trustManagers = instance3.getTrustManagers();
    for (int i = 0; i < trustManagers.length; i++) {
        if (trustManagers[i] instanceof X509TrustManager) {
            this.a = (X509TrustManager) trustManagers[i];
            return;
        }
    }
    throw new Exception("Couldn't initialize");
}
 
Example 20
Project: ProyectoPacientes   File: BlobRegressionTest.java   View Source Code Vote up 4 votes
public void testBug5490() throws Exception {

        createTable("testBug5490", "(pk INT NOT NULL PRIMARY KEY, blobField BLOB)");
        String sql = "insert into testBug5490 values(?,?)";

        int blobFileSize = 871;
        File blobFile = newTempBinaryFile("Bug5490", blobFileSize);

        this.pstmt = this.conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.pstmt.setInt(1, 2);
        FileInputStream fis = new FileInputStream(blobFile);
        this.pstmt.setBinaryStream(2, fis, blobFileSize);
        this.pstmt.execute();
        fis.close();
        this.pstmt.close();

        this.rs = this.stmt.executeQuery("SELECT blobField FROM testBug5490");

        this.rs.next();

        byte[] returned = this.rs.getBytes(1);

        assertEquals(blobFileSize, returned.length);

    }