当我运行我的 jar 文件时,它不起作用,因为它找不到books.csv,但它存在于指定的源中

When I run my jar file, it doesn't work because it can't find books.csv, but it exists at the specified source

提问人:Edwin Ryerson 提问时间:4/4/2023 最后编辑:Edwin Ryerson 更新时间:4/4/2023 访问量:39

问:

我的 jar 文件无法运行。它在引用主包中的文件时给出错误。

java -jar IA.jar

file not found
java.io.FileNotFoundException: src/main/books.csv (No such file or directory)
    at java.base/java.io.FileInputStream.open0(Native Method)
    at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158)
    at java.base/java.util.Scanner.<init>(Scanner.java:641)
    at main.Library.loadScanner(Library.java:98)
    at main.Library.loadBooks(Library.java:119)
    at main.Library.<init>(Library.java:25)
    at main.Main.main(Main.java:17)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Scanner.hasNext()" because "scanner" is null
    at main.Library.loadScanner(Library.java:107)
    at main.Library.loadBooks(Library.java:119)
    at main.Library.<init>(Library.java:25)
    at main.Main.main(Main.java:17)

主类如下所示:

public class Main {
    private final static String root = "src/main/";
    public static void main(String[] args) throws IOException {
        String[] dirs = {root + "books.csv", root + "teacher.csv", root + "users.csv"};
        Library library = new Library(dirs); // libary instance

        new HomePage(library); // open GUI
    }
}

库方法 loadScanner() 用于打开充当一种虚拟数据库的.csv文件。

private ArrayList<String[]> loadScanner(String dir) {
        File myFile1 = new File(dir);
        Scanner scanner = null;
        try {
            scanner = new Scanner(myFile1);
            scanner.useDelimiter(",");
        } catch (FileNotFoundException e) {
            System.out.println("file not found");
            e.printStackTrace();
        }

        ArrayList<String[]> data = new ArrayList<>();

        while (scanner.hasNext()) {

            String line = scanner.next();

            String[] r = line.trim().split(",");
            data.add(r);
        }
        return data;
    }
Java CSV 文件 jar java.util.scanner

评论

0赞 Erwin 4/4/2023
代码是什么?
0赞 Edwin Ryerson 4/4/2023
@Erwinpublic class Main { private final static String root = "src/main/"; public static void main(String[] args) throws IOException { String[] dirs = {root + "books.csv", root + "teacher.csv", root + "users.csv"}; Library library = new Library(dirs); // libary instance new HomePage(library); // open GUI } }
0赞 Erwin 4/4/2023
把它放在问题中,我不能这样看
0赞 Erwin 4/4/2023
导致错误的行是什么?at main.Library.loadScanner(Library.java:98)
1赞 life888888 4/4/2023
@Edwin瑞尔森,首先决定你想实现什么?(a) Jar 读取放置在某个目录中的book.csv文件 (b) Jar 读取与 Jar 位于同一目录中的book.csv文件 (c) Jar 读取 Jar 中的book.csv文件。

答: 暂无答案