Search code examples
javafile-read

FileReader not working in Java


I'm trying to read from a file and it's not working correctly. I've looked at many examples on here and the method I'm using is borrowed from an answer to someone else's question. I'm aware you can use bufferedreader but I'd like to stick with what I know and am learning in my classes right now. When I run this code I just get a blank line, but the file contains 4 lines of information.

import java.io.*;
import java.util.Scanner;
import java.lang.StringBuilder;
import java.io.File;
import java.io.FileInputStream;

public class fileWriting{
   public static void main(String[] args) throws IOException{
     //Set everything up to read & write files
     //Create new file(s)
     File accInfo = new File("accountInfo.txt");
     //Create FileWriter
     Scanner in = new Scanner(new FileReader("accountInfo.txt"));

     String fileString = "";
     //read from text file to update current information into program
     StringBuilder sb = new StringBuilder();
     while(in.hasNext()) {
       sb.append(in.next());
     }
     in.close();
     fileString = sb.toString();
     System.out.println(fileString);  
  }
}

My file contains the following text:

name: Howard

chequing: 0

savings: 0

credit: 0


Solution

  • One of the advantages of using something like BufferedReader over using Scanner is that you will get an exception if the read fails for any reason. That’s a good thing—you want to know when and why your program failed, rather than having to guess.

    Scanner does not throw an exception. Instead, you have to check manually:

    if (in.ioException() != null) {
        throw in.ioException();
    }
    

    Such a check probably belongs near the end of your program, after the while loop. That won’t make your program work, but it should tell you what went wrong, so you can fix the problem.

    Of course, you should also verify that accountInfo.txt actually has some text in it.