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
Before java 7, we used to write explicit code for closing file in finally block by using try-finally block like this (As we have been doing in other programs) >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
InputStream inputStream = null;
try{
inputStream = new FileInputStream("c:/txtFile.txt");
//code......
}finally{
if(inputStream!=null)
inputStream.close();
}
}
}
|
In java 7, using Try-with-resources >
- we need not to write explicit code for closing file.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) {
//code...
}
}
}
|
Now, question comes why we need not to close file when we are using Try-with-resources?
Because FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interface’s close method automatically closes resources which are no longer needed.)
Which classes can be used inside Try-with-resources?
All the classes which implements AutoCloseable interface can be used inside Try-with-resources.
Program to Read text from file using FileInputStream and Try with resource provided in java 7
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** JavaMadeSoEasy.com */
public class ReadFileUsingFileInputStream {
public static void main(String... args) {
//Try with resource in java 7
try (InputStream fis = new FileInputStream("c:/myFile.txt")) {
System.out.println("Reading from text file using FileInputStream "
+ "and tryWithResource provided in java 7 > ");
int ch;
while ((ch = fis.read()) != -1) { // read till end of file
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* OUTPUT
Reading from text file using FileInputStream and tryWithResource provided in java 7 >
You are learning File IO from javaMadeSoEasy.com
*/
|
RELATED LINKS>
Program to Read text from file in String using BufferedInputStream and Try with resource provided in java 7
Read text from file using FileInputStream in java file IO
Read text from file using BufferedInputStream (and FileInputStream) in java file IO
Labels:
Core Java
File IO/File handling