这是我读取文本文件的代码。当我运行此代码时,输出一直显示“找不到文件。”,这是消息FileNotFoundException
。我不确定这段代码有什么问题。
显然这是java的一部分。对于整个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;
}
如果您使用 Eclipse 或 NetBeans 等 IDE,那么您应该拥有a.txt
文件位于项目的根目录中。 (并且不在您的文件夹中.class
文件已构建或其他任何地方)
如果没有,您应该指定该文件的绝对路径。
Edit:
你会把.txt
文件与以下文件位于同一位置.class
(通常也是.java
文件,因为您在同一文件夹中编译)编译文件,如果您手动编译它javac
。这是因为它使用相对路径,路径告诉JVM可执行文件所在的路径。
如果您使用某些 IDE,它会使用 Makefile 或类似 Windows 的文件为您生成编译文件,并考虑它的默认文件结构,因此他知道相对路径从项目的根文件夹开始。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)