Это мой код для чтения текстового файла. Когда я запускаю этот код, выводится сообщение «Файл не найден», что является сообщением об исключении 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;
}