如何使用Java中的扫描程序读取文本文件?

这是我读取文本文件的代码。 当我运行此代码时,输​​出会一直显示“File not found。”,这是FileNotFoundException的消息。 我不确定这段代码中的问题是什么。

显然这是java的一部分。 对于整个java文件,它要求用户输入内容并使用输入作为名称创建文本文件。 之后,用户应该再次输入之前创建的文本文件的名称(假设用户输入正确),然后程序应该读取文本文件。 我已正确完成程序的其他部分,但问题是当我再次输入名称时,它只是找不到文本文件,尽管它们位于同一文件夹中。

 public static ArrayList readFile() { try { // The name of the file which we will read from String filename = "a.txt"; // Prepare to read from the file, using a Scanner object File file = new File(filename); Scanner in = new Scanner(file); ArrayList shops = new ArrayList(); // Read each line until end of file is reached while (in.hasNextLine()) { // Read an entire line, which contains all the details for 1 account String line = in.nextLine(); // Make a Scanner object to break up this line into parts Scanner lineBreaker = new Scanner(line); // 1st part is the account number try { int shopNumber = lineBreaker.nextInt(); // 2nd part is the full name of the owner of the account String owner = lineBreaker.next(); // 3rd part is the amount of money, but this includes the dollar sign String equityWithDollarSign = lineBreaker.next(); int total = lineBreaker.nextInt(); // Get rid of the dollar sign; // we use the subtring method from the String class (see the Java API), // which returns a new string with the first 'n' characters chopped off, // where 'n' is the parameter that you give it String equityWithoutDollarSign = equityWithDollarSign.substring(1); // Convert this balance into a double, we need this because the deposit method // in the Account class needs a double, not a String double equity = Double.parseDouble(equityWithoutDollarSign); // Create an Account belonging to the owner we found in the file DogShop s = new DogShop(owner); // Put money into the account according to the amount of money we found in the file s.getMoney(equity); s.getDogs(total); // Put the Account into the ArrayList shops.add(s); } catch (InputMismatchException e) { System.out.println("File not found1."); } catch (NoSuchElementException e) { System.out.println("File not found2"); } } } catch (FileNotFoundException e) { System.out.println("File not found"); } // Make an ArrayList to store all the accounts we will make // Return the ArrayList containing all the accounts we made return shops; } 

嗯..显然该文件不存在或无法找到。 尝试使用完整路径。 除非a.txt在您当前的工作目录中,否则您可能在未指定路径时从错误的目录中读取。

如果您在某些IDE(如Eclipse或NetBeans)中工作,则应该在项目的根目录中包含该a.txt文件。 (而不是在构建.class文件的文件夹中或其他任何位置)

如果不是,则应指定该文件的绝对路径。


编辑:
你可以将.txt文件与.class放在同一个地方(通常也是.java文件,因为你在同一个文件夹中编译)编译文件,如果你用javac手工编译它。 这是因为它使用相对路径,路径告诉JVM可执行文件所在的路径。

如果您使用某些IDE,它将使用Makefile或类似的东西为您生成编译的文件,并将其视为默认文件结构,因此他知道相对路径从项目的根文件夹开始。

我建议将文件加载为Resource并将输入流转换为字符串。 这将使您可以灵活地将文件加载到相对于类路径的任何位置

如果为Scanner对象提供String,则会将其作为数据读入。 也就是说,“a.txt”不会打开名为“a.txt”的文件。 它字面上读取字符’a’,’。’,’t’等等。

这是根据Core Java第I卷第3.7.3节。

如果我找到了解读实际路径的解决方案,我将返回并更新此答案。 本文提供的解决方案是使用

 Scanner in = new Scanner(Paths.get("myfile.txt")); 

但我不能让它工作,因为编译器不会将Path识别为变量。 也许我错过了一个导入声明。

这应该可以帮助你..:

 import java.io.*; import static java.lang.System.*; /** * Write a description of class InRead here. * * @author (your name) * @version (a version number or a date) */ public class InRead { public InRead(String Recipe) { find(Recipe); } public void find(String Name){ String newRecipe= Name+".txt"; try{ FileReader fr= new FileReader(newRecipe); BufferedReader br= new BufferedReader(fr); String str; while ((str=br.readLine()) != null){ out.println(str + "\n"); } br.close(); }catch (IOException e){ out.println("File Not Found!"); } } } 

另一件事……使用System.err.println("Error Message Here")而不是System.out.println("Error Message Here") System.err.println("Error Message Here") 。 这将允许您通过以红色显示错误(即System.err.println()内的所有内容System.err.println()来区分错误和正常代码function之间的差异。

注意 :它也适用于System.err.print("Error Message Here")