java - 线程 "main"java.io.FileNotFoundException I/O Java 中的奇怪异常

标签 java file-io filenotfoundexception

我在尝试读取文件时出现此错误:

Exception in thread "main" java.io.FileNotFoundException: \src\product.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at dao.Inventory.readFile(Inventory.java:30)
at view.InventoryView.init(InventoryView.java:33)
at view.InventoryView.<init>(InventoryView.java:21)
at view.InventoryView.main(InventoryView.java:211)

但问题是,我的 src 文件夹中有 product.txt。

我的代码如下:

  public void readFile() throws IOException {
            // input file must be supplied in the first argument
            InputStream istream;
                    File inputFile = new File("\\src\\product.txt");
                    istream = new FileInputStream(inputFile);

                    BufferedReader lineReader;
                lineReader = new BufferedReader(new InputStreamReader(istream));
                    String line;

                        while ((line = lineReader.readLine()) != null) {

                StringTokenizer tokens = new StringTokenizer(line, "\t");

                // String tmp = tokens.nextToken();
                // System.out.println("token " + tmp);
                ActionProduct p = new ActionProduct();
                prodlist.add(p);
                String category = p.getCategory();
                category = tokens.nextToken();
                System.out.println("got category " +category);

                int item = p.getItem();
                item = Integer.parseInt(tokens.nextToken());

                String name = p.getName();
                System.out.println("got name " +name);

                double price = p.getPrice();
                price = Double.parseDouble(tokens.nextToken());

                int units = p.getUnits();
                units = Integer.parseInt(tokens.nextToken());
            }
        }

我认为我的代码没有任何问题。另外,我看到了一篇关于隐藏扩展的类似帖子,如 FILE.TXT.TXT,你将如何在 MacOSX 中显示隐藏扩展??有什么建议么? (除了隐藏扩展问题,还会有其他问题吗?)

最佳答案

/src/product.txt 是绝对路径,因此程序会尝试在您的根路径(/)的 src 文件夹中查找该文件。使用 src/product.txt 以便程序将其用作相对路径。

关于java - 线程 "main"java.io.FileNotFoundException I/O Java 中的奇怪异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953328/

相关文章:

java - 对象列表与消费者之间的性能差异

Java 创建正则表达式组

java - Java Android 中的 EOFException?需要帮助

java - 如何读取位于项目文件夹Java中的文件

android - 打开失败 : EACCES (Permission denied)

java - 由于池初始化期间发生 HikariPool 异常,无法部署 Spring boot 2 应用程序

java - Spring中如何使用Singleton对象?

php - 哪个更快 : glob() or opendir()

java - 从 txt.file 读入二维数组的数据值被翻转

java - FileSystemResource : java. io.FileNotFoundException