Java,无法从文件读取

时间:2019-11-12 17:27:38

标签: java

无论何时输入名称,都会创建文件并且在其中显示行,但是当我使用display方法时,它会吐出该错误,并且我不确定我的问题在哪里,并且我对Java有点陌生。我在另一个类中有一种方法可以保存行,但我认为这不是我的问题所在,而且我有点受阻,不胜感激。

    package X;

    import java.util.Scanner;
    import java.io.*;

    public class FileDisplay {
        String filename;

        public FileDisplay(String name) {name = filename;}

        public void display() throws IOException {
            File file = new File(filename);
            Scanner inputFile = new Scanner(file);
            while (inputFile.hasNext()) {
                String str = inputFile.nextLine();
                System.out.println(str);
            }
            inputFile.close();
        }


    }

我运行了代码,每次都出现此错误:

Exception in thread "main" java.lang.NullPointerException
    at java.base/java.io.File.<init>(File.java:276)
    at ES1036a.Lab6.FileDisplay.display(FileDisplay.java:12)
    at ES1036a.Lab6.FilesDemo.main(FilesDemo.java:27)

这是演示类:

    package X;

    import java.util.Scanner;
    import java.io.*;
    public class FilesDemo {
        public static void main(String[] args) throws IOException {
            String filename = "lines.txt";

            Scanner keyboard = new Scanner(System.in);
            System.out.println("What's the filename?");

            filename = keyboard.nextLine();

            FileSave FilesDemo = new FileSave(filename);
            FilesDemo.save("1-Lorem ipsum dolor sit amet\n" +
                    "2-Consectetuer adipiscing elit\n" +
                    "3-Sed diam nonummy nibh euismod tincidunt\n" +
                    "4-Ut wisi enim ad minim veniam\n" +
                    "5-Quis nostrud exerci tation ullamcorper\n" +
                    "6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat\n" +
                    "7-Duis autem vel eum iriure dolor in hendrerit\n" +
                    "8-Vel illum dolore eu feugiat nulla facilisis at vero eros");


            FileDisplay FilesDemo2 = new FileDisplay(filename);

            FilesDemo2.display();
        }
    }

1 个答案:

答案 0 :(得分:2)

在FileDisplay的构造函数中,您未分配名为“ filenamed”的属性,请按以下方式进行纠正:

public FileDisplay(String name) {
    /*  wrong
    the parameter String "name" is reassigned but you need
    to assing the class attribute "filneame", this line is wrong:
    name = filename;
    */

    // correct 
    filename = name;
}