英文:
Reading Text File WIith Scanner (Java)
问题
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();
}
}
"p1.txt"文件中的内容如下:
p, -4, 5
q, 19, 8
r, 3, 0
x, 7.4, -1
y, -2.3, -16.5
z, 0, 1
出于某种原因,我的代码无法读取文本文件,并给出以下输出:
The file p1.txt
contains the following lines:
Error opening the file p1.txt
我不确定我需要做什么。
英文:
My Text file is called p1 and it contains:
p, -4, 5
q, 19, 8
r, 3, 0
x, 7.4, -1
y, -2.3, -16.5
z, 0, 1
My code is:
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();
}
}
For some reason my code can't read my text file and gives me the following output:
The file p1.txt
contains the following lines:
Error opening the file p1.txt
I'm not sure what I need to do.
答案1
得分: 1
这是因为您的文件 "p1.txt"
不存在。请检查文件的位置。它应该放在同一个目录中。
英文:
This is because your file "p1.txt"
does not exists. Check the location of your file. It should be placed in same directory.
答案2
得分: 1
确保txt文件与项目在同一个文件夹中,如果不在,请提供路径。
英文:
Make sure that txt file is in the same folder as the project, if not give a path to it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论