用扫描仪读取文本文件(java)

kcwpcxri  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(303)

我的文本文件名为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

我不知道我需要做什么。

os8fio9y

os8fio9y1#

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

67up9zun

67up9zun2#

确保txt文件与项目位于同一文件夹中,如果没有,请提供指向该文件的路径。

相关问题