【问题标题】:Trying to input a file in java using a buffered-reader. Getting a FileNotFoundError尝试使用缓冲读取器在 java 中输入文件。获取 FileNotFoundError
【发布时间】:2017-09-29 14:29:08
【问题描述】:

这是我在尝试解析传入文件时遇到的错误:

解析文件时出错。 java.io.FileNotFoundException: input.txt (系统找不到文件 指定的) 在 java.io.FileInputStream.open0(本机方法) 在 java.io.FileInputStream.open(未知来源) 在 java.io.FileInputStream.(未知来源) 在 java.io.FileInputStream.(未知来源) 在 java.io.FileReader.(未知来源) 在 MovieDatabaseManager.parseInputFile(MovieDatabaseManager.java:47) 在 MovieDatabaseManager.(MovieDatabaseManager.java:32) 在 MovieDatabaseManager.main(MovieDatabaseManager.java:206)

代码如下:

public MovieDatabaseManager(String file)
{
    this();
    parseInputFile(file); //populates database with list of movies
}

/**
 * Parses the input file so that you can add all of items found in the list 
in alphabetical order by title.
 */
private void parseInputFile(String file)
{
    //Create a file input stream
    Movie m;
    String instr;

    try 
    {
        //Create input reader
        BufferedReader in = new BufferedReader(new FileReader(file));
        while (in.ready())
        {
            instr = in.readLine();

            //Try to parse the movie using the appropriate movie 
            //constructor.  If it fails, an exception is caught
            try 
            {
                m = new Movie(instr);

                ////////////////////////////////////////////////////
                //Add code to insert m here into your list
                ////////////////////////////////////////////////////

            } 
            catch (InvalidMovieException e) 
            {
                System.out.println("Invalid movie string " + instr + " in 
`enter code here`file " + file);
            }

        }
    } 
    catch (IOException io) 
    {
        System.err.println("Error in Parsing file.");
        io.printStackTrace();   
    }
    }

【问题讨论】:

  • 您的文件路径可能不正确
  • @pruntlar 说了什么。您的程序几乎可以肯定没有在正确的位置查找文件。
  • 您需要了解相对文件名当前目录是什么。它们不是特定于 Java 的,而是通用的计算概念,在您有效处理文件之前必须了解这些概念。

标签: java input buffered


【解决方案1】:

您需要使用资源的完整限定路径名来获取它。

例如:C:/dur/dir/file.txt

否则,相对路径可以用于执行的jar文件的同一层次结构中的文件。

【讨论】:

  • 相对路径是相对于当前工作目录的。它与“执行的 jar 文件的相同层次结构”无关。
  • 当从 Jar 运行时从 Jar 路径,从 Eclipse 运行时从工作目录,如果使用 getClass().getResource() 从类路径
猜你喜欢
  • 2015-04-10
  • 2011-04-20
  • 2016-01-23
  • 2020-10-05
  • 2013-07-16
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
相关资源
最近更新 更多