Issue
I am a very novice programmer trying to read a text file in Java Eclipse.
Here is my code:
package readFromfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class justDo {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(System.getProperty("user.dir"));
File file = new File(System.getProperty("user.dir") +
"/src/report.txt");
Scanner hemp = new Scanner(file);
System.out.println(hemp);
}
}
Instead of reading a text file and displaying the file's contents in the console I get this:
C:\Users\Vanessa\eclipse-workspace\readFromfile
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=false][need input=false][source closed=false][skipped=false][group
separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-
\E][positive suffix=][negative suffix=][NaN string=\QNaN\E][infinity
string=\Q?\E]
Can someone please explain why I am getting this and explain how to properly read a text file in Java Eclipse? Please help. Thank you all so much in advance.
Solution
You are printing the Scanner
object, not the File
read.
To do that you have to run over the Scanner
content, here is an example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(System.getProperty("user.dir"));
File file = new File(System.getProperty("user.dir") + "/src/report.txt");
Scanner hemp = new Scanner(file);
while (hemp.hasNextLine()) {
System.out.println(hemp.nextLine());
}
}
}
If you want to read more about the Scanner
functions you can see the API docs:
Answered By - Beto Rodriguez
Answer Checked By - Willingham (JavaFixing Volunteer)