Working with Files JDK 1.6 or older

there is an easy way to work with files in JDK 8 but in older version when we need to read the files there was a quick coding line we had to do. in here I brought a simple example on how to open and read a text file in older versions of java.


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Unknown_
*/
public class TextFile_OlderJDK {

public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("myFile.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("" + line);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TextFile_OlderJDK.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TextFile_OlderJDK.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
e.printStackTrace();
} finally {

// this will run every time
try {
if (reader != null) {
reader.close();
}
} catch (IOException ex) {
Logger.getLogger(TextFile_OlderJDK.class.getName()).log(Level.SEVERE, null, ex);
}

}

}

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s