1

So I have a file called boynames.txt with everything written into it, if I go like this:

   File getNames = new File("boynames.txt"):4

Then I just get a new file called "boynames.txt" , but how do I get access to a file that I have already written inside of it already, but want access to it?

NULLPTR
  • 37
  • 4
  • Possible duplicate of [How to read a file in Java with specific character encoding?](https://stackoverflow.com/questions/12096844/how-to-read-a-file-in-java-with-specific-character-encoding) – Kwright02 May 06 '18 at 03:11

2 Answers2

1

Is this what you're looking for? You can read the file using a Scanner.

Source code:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

class Demo 
{
    public static void main(String[] args) throws FileNotFoundException 
    {
        File f = new File("boynames.txt");
        Scanner names = new Scanner(f);

        while (names.hasNextLine())
            System.out.println(names.nextLine());
    }
}

Output:

demo > javac Demo.java
demo > java Demo
Tim
Joe
Bobby
0

You could use java.io.FileReader:

import java.io.*;
//in a try catch do:
with(BufferedReader r = new BufferedReader(new FileReader("boynames.txt"))) {
  String line = "";
  while ((line = r.readLine()) != null) {
    System.out.println(line);
  }
}

Ref: 1. https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html 2. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html

Keenan Gebze
  • 1,366
  • 1
  • 20
  • 26