Reputation: 37
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?
Upvotes: 1
Views: 50
Reputation: 82
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
Upvotes: 1
Reputation: 1403
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
Upvotes: 0