如何在Java Eclipse中读取文本文件?

3

我是一位非常初级的程序员,试图在Java Eclipse中读取文本文件。

这是我的代码:

 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);



  }
}

不是读取文本文件并在控制台中显示文件内容,而是获得了这个结果:
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]

能否有人解释一下我为什么会收到这个错误,并说明如何在Java Eclipse中正确读取文本文件?请帮忙。非常感谢。

2个回答

2
你正在打印Scanner对象,并非读取的File。 要打印内容,你需要遍历Scanner对象。以下是一个示例:
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());
        }
    }
}

如果您想了解更多有关 Scanner 功能的信息,可以查看 API 文档:


谢谢,兄弟!这帮了我很多。真的非常感激。 - joshua matthews

1
使用Java的BufferedReader。只需搜索“BufferedReader java example”并查看BufferedReader api即可。它将允许您读取文件,教程/示例将告诉您如何打印文件的各个方面。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接