【问题标题】:Reading Text File WIith Scanner (Java)使用扫描仪读取文本文件 (Java)
【发布时间】:2020-09-03 07:56:55
【问题描述】:

我的文本文件名为 p1,它包含:

p, -4, 5
q, 19, 8
r, 3, 0
x, 7.4, -1
y, -2.3,  -16.5
z, 0, 1

我的代码是:

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

public class Driver {

    public static void main(String[] args) {
        
        String fileName = "p1.txt";
        Scanner inputStream = null;
        System.out.println("The file " + fileName + "\ncontains the following lines: \n");
        
        try
        {
            inputStream = new Scanner(new File(fileName));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error opening the file " + fileName);
            System.exit(0);
        }
        while(inputStream.hasNextLine())
        {
            String line = inputStream.nextLine();
            System.out.println(line);
        }
        inputStream.close();
    }

}

由于某种原因,我的代码无法读取我的文本文件并给出以下输出:

The file p1.txt
contains the following lines: 

Error opening the file p1.txt

我不确定我需要做什么。

【问题讨论】:

  • 根据您的代码,当找不到文件时会写入此消息:catch(FileNotFoundException e) { System.out.println("Error opening the file " + fileName); System.exit(0); }。您的文件应该在当前工作目录中,或者应该使用绝对路径,
  • 找到文件后,我建议使用 BufferedReader 来读取文本文件,而不是流。
  • 快速确定您是否拥有正确文件的方法是使用 File#getCanonicalPath()。您必须与流分开创建文件对象才能使用它。

标签: java file text java.util.scanner


【解决方案1】:

确保 txt 文件与项目在同一个文件夹中,如果没有给出它的路径。

【讨论】:

    【解决方案2】:

    这是因为您的文件 "p1.txt" 不存在。检查文件的位置。它应该放在同一目录中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多