Program to Read text from file in String using BufferedInputStream and Try with resource provided in java 7



We will read c:/myFile.txt


c:/myFile.txt looks like this >
You are learning File IO from javaMadeSoEasy.com


Read :Try-with-resources in java - java.lang.AutoCloseable interface

Should we close both FileInputStream and BufferedInputStream ?




Using multiple resources inside Try-with-resources >
Try-with-resources allows us to use multiple resources inside it, all that we need to do is separate resources by semicolon (;)
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
   public static void main(String[] args) throws IOException {
          try (InputStream inputStream = new FileInputStream("c:/txtFile.txt") ;
                InputStream bInputStream = new BufferedInputStream(inputStream) ){
                 //code...
          }
   }
}


Program to Read text from file in String using BufferedInputStream and Try with resource provided in java 7 >
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** JavaMadeSoEasy.com */
public class ReadFileUsingBufferedInputStream {
   public static void main(String... args) {
          //Try with resource in java 7
          try (InputStream fis = new FileInputStream("c:/myFile.txt");
                       InputStream bis = new BufferedInputStream(fis) ) {
                 System.out.println("Reading from text file using BufferedInputStream "
                              + "and tryWithResource provided in java 7 > ");
                 int ch;
                 while ((ch = bis.read()) != -1) { // read till end of file
                       System.out.print((char) ch);
                 }
          } catch (IOException e) {
                 e.printStackTrace();
          }
   }
}
/*OUTPUT
Reading from text file using BufferedInputStream and tryWithResource provided in java 7 >
You are learning File IO from javaMadeSoEasy.com   
*/





RELATED LINKS>

Program to Read text from file using FileInputStream and Try with resource provided in java 7


Write String to file using BufferedOutputStream (and FileOutputStream) in java file IO

No comments:

Post a Comment