【发布时间】: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