package com.as400samplecode; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadBufferedInputStream { public static void main(String[] args) { File file = new File("data/newFile.txt"); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); //process each character at a time while( bis.available() > 0 ){ System.out.print((char)bis.read()); } } catch (IOException e) { e.printStackTrace(); } finally { try { fis.close(); bis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
Another more efficient way using a byte array
package com.as400samplecode; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadBufferedInputStream { public static void main(String[] args) { File file = new File("data/newFile.txt"); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); byte[] buffer = new byte[1024]; int bytesRead = 0; // Keep reading from the file while there is any content // when the end of the stream has been reached, -1 is returned while ((bytesRead = bis.read(buffer)) != -1) { // Process the chunk of bytes read // in this case we just construct a String and print it out String chunk = new String(buffer, 0, bytesRead); System.out.print(chunk); } } catch (IOException e) { e.printStackTrace(); } finally { try { fis.close(); bis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.