gpt4 book ai didi

java - 如何使用Java中的扫描仪读取文本文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:20:03 26 4
gpt4 key购买 nike

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

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

public static ArrayList<DogShop> 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<DogShop> shops = new ArrayList<DogShop>();

// 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;
}

最佳答案

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

如果没有,您应该指定该文件的绝对路径。


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

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

关于java - 如何使用Java中的扫描仪读取文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6082586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com