使用扫描仪读取文本文件(Java)
我的文本文件名为p1,它包含:使用扫描仪读取文本文件(Java),java,file,text,java.util.scanner,Java,File,Text,Java.util.scanner,我的文本文件名为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) {
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
我不确定我需要做什么。这是因为您的文件
“p1.txt”
不存在。检查文件的位置。它应该放在同一个目录中。这是因为您的文件“p1.txt”
不存在。检查文件的位置。它应该放在同一个目录中。确保txt文件与项目在同一个文件夹中,如果没有给出路径。确保txt文件与项目在同一个文件夹中,如果没有给出路径。根据您的代码,当找不到文件时会写入此消息:catch(FileNotFoundException e){System.out.println(“打开文件“+文件名时出错);System.exit(0);}
。您的文件应该在当前工作目录中,或者应该使用绝对路径。一旦找到文件,我建议使用BufferedReader来读取文本文件,而不是流。确定文件是否正确的快速方法是使用file#getCanonicalPath()。您必须与流分开创建文件对象才能使用它。根据您的代码,在找不到文件时会写入此消息:catch(FileNotFoundException e){System.out.println(“打开文件时出错”+fileName);System.exit(0);}
。您的文件应该在当前工作目录中,或者应该使用绝对路径。一旦找到文件,我建议使用BufferedReader来读取文本文件,而不是流。确定文件是否正确的快速方法是使用file#getCanonicalPath()。您必须与流分开创建文件对象才能使用它。