Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 38 Reading Files with the File Reader
- //App.java
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- //You can read files using the scanner class(see previous tutorial 33) which is a bit less cumbersome,
- //however, this is still important because you can change the code/adapt it so it will read files of all different formatss like the binary format.
- //so what we are going to write here is very flexible despite cumbersome.
- public class App {
- public static void main(String[] args) {
- File file = new File("text.txt"); //step 1.create new file
- BufferedReader br = null;
- try {
- FileReader fr = new FileReader(file);
- br = new BufferedReader(fr); //5. Do Buffering, right click on error, import what you need
- String line; //
- ///line = br.readLine(); //then click on error and add catch clause surround with try catch
- //6. want a while loop so the App reads every line in the text.
- while( (line = br.readLine())!= null ){ // want the while loop to stop reading when their are no more lines: "null"
- System.out.println(line);
- }
- } catch (FileNotFoundException e) {
- System.out.println("File not found: " + file.toString());
- } //2. read the file with FileReader
- //3.(ctrl+shift+O ) to import "import java.io.File; import java.io.FileReader;"
- ///it will throw a filenotfound exception, click the error and "surround it with trycatch"
- catch (IOException e) {
- System.out.println("unable to read file: " + file.toString());
- }
- finally { //finally block is always going to be executed everytime, even if exceptions are thrown
- try {
- br.close();
- } catch (IOException e) {
- System.out.println("unable to close file: " + file.toString());
- }
- catch(NullPointerException ex){
- //File was probably never opened!
- }
- }
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- //text.txt
- first line
- second line
- third line
- //---------------------------------------------------------------------------------------------------------------------------------------
- /*Run Results:
- first line
- second line
- third line
- */
- //---------------------------------------------------------------------------------------------------------------------------------------
- /*
- Error Message (if u purposely get an error by switching the name of the text[ie: tefxt.txt) so it the program can't find the file):
- File not found: tefxt.txt
- */
- //note: there is a language feature in Java.7 that can simplify this exceptions nested mess: we will go over it in the next tutorial.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement