3

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.

0

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man! This helped out alot. Really apreciate it.
1

Use Java's BufferedReader. Just search up BufferedReader java example and look at the BufferedReader api. It'll let you read files and the tutorial/example will let you know how to print out aspects of the file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.