问题描述
我的文本文件称为p1,其中包含:
p,-4,5
q,19,8
r,3,0
x,7.4,-1
y,-2.3,-16.5
z,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
我不确定该怎么做。
解决方法
这是因为您的文件"p1.txt"
不存在。检查文件的位置。它应该放在同一目录中。
如果没有提供txt文件的路径,请确保txt文件与项目位于同一文件夹中。