所以我使用了 DataInputStream、FileInputStream、BufferInputStream、FileReader、BufferedReader、Scanner,凡是你能想到的。它们都会抛出 FileNOtFoundException 或 CorruptedStreamException。
异常 java.io.FileNotFoundException: java.io.FileReader@253498.data (系统找不到指定的文件) 被抛出在使用文件名“Accounts.txt”初始化 FileReader 的行上,该文件是我在 bin 中初始化的文件,其中包含所需的文本。
import java.io.*;
import java.util.ArrayList;
/**
* Class to load account files
*/
public class AccountLoader {
/**
* Add an account file
* @param newAccount
*/
public static void addAcountFile(Account newAccount) {
try {
PrintWriter out = new PrintWriter(new File("Accounts.txt"));
out.print(" " + newAccount.getOwner().getName());
System.out.println("saved account " + newAccount.getOwner().getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static ArrayList<Account> loadAccountsList() throws EOFException, IOException, ClassNotFoundException{
ArrayList<Account> accounts = new ArrayList();
FileReader load = new FileReader("Accounts.txt");
String file = load.toString();
String[] accountsload = file.split(" ");
for (String string : accountsload){
accounts.add(loadAccount(string + ".data"));
}
load.close();
return accounts;
}
public static void save(Account account) {
String filename = account.getOwner().getName() + ".data" ;
if (filename != null) {
try {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(account);
out.flush();
out.close();
}
catch (IOException e) { System.out.println(e); }
}
}
public static Account loadAccount(String filename) {
Account newAccount = null;
if (filename != null) {
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
newAccount = (Account)in.readObject();
in.close();
}
catch (Exception e) { System.out.println(e); }
}
return newAccount;
}
}
最佳答案
您可能需要将文本文件放入“项目根”文件夹(包含 src
和 bin
的文件夹),而不是 bin
。文件夹。如果您从 Eclipse 运行它,那么这绝对是您需要做的,因为从 Eclipse 运行的 Java 项目的上下文始终是该项目的 Eclipse 项目文件夹。
当您要求 Java 按名称打开文件而不指定路径时,JVM 将在其当前工作目录中查找该文件。当前工作目录会根据您运行程序的方式而变化,在您的情况下,“bin”文件夹看起来不是您当前的工作目录。
关于java - 从文本文件读取会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926363/