1

I have a txt file that I want to load into Java, and I've been trying to use

PrintWriter writer = new PrintWriter(new File("location/name.txt"));

But instead of loading the existing file, it writes over the old one and creates a new blank one. How can I load the existing file into Java?

jpthesolver2
  • 1,107
  • 1
  • 12
  • 22
  • This question makes little sense. You can't "load a PrintWriter". A `PrintWriter` is something for **writing** a file. That's what the "write" in `PrintWriter` refers to. If you want to read a text file you need to use a `Reader` of some kind. However, since we don't know what you are *actually* trying to do, I don't think we can answer this. – Stephen C Jan 07 '18 at 02:10
  • If you want to read a file you need to use a Reader not a Writer. – eckes Jan 07 '18 at 02:31

3 Answers3

1

You must use a Reader instead of Writer.

There are various ways to read a text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Each class has its own purpose e.g. BufferedReader is used to buffer data for reading fast, and Scanner provides parsing ability.

Example using BufferedReader :

public class ReadFile {

     public static void main(String[] args)throws Exception
      {
      File file = new File("C:\\location\\test.txt");

      BufferedReader br = new BufferedReader(new FileReader(file));

      String st;
      while ((st = br.readLine()) != null)
        System.out.println(st);
      }
}
Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53
0

I think this is what you want:

    try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("location/yourFileName.txt", true)))) {
       pw.println("what you want to write to the file");
       pw.close();
    } catch (IOException e) {
      //Exception handling goes here.
    }

The FileWriter constructor's second argument is what sets the append condition. Also, as stated in the comments(and pretty obvious) that you need a reader to load or input data.

Shankha057
  • 1,296
  • 1
  • 20
  • 38
-3

You can try File f = new File(filePathString);

Kevin Lin
  • 71
  • 2
  • 8