因此,我使用了DataInputStream,FileInputStream,BufferInputStream,FileReader,BufferedReader,Scanner等名称。它们都抛出FileNOtFoundException或CorruptedStreamException。从文本文件中读取抛出异常
异常 java.io.FileNotFoundException:[email protected](系统找不到指定的文件) 被扔在其中的FileReader与文件名初始化“Accounts.txt”行,这是一个我已经初始化的文件,在文件箱中,需要它的文本。
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;
}
}
您是否使用命令行运行? –
我99%确定你没有在正确的位置查找文件,用户目录,就像99%的经常***问这个问题的人(如果我有一个每季度一次......)。通过运行这一行找到用户目录:'System.out.println(System.getProperty(“user.dir”));' –
@HovercraftFullOfEels如果我有一个季度,每次你是对的... – MadProgrammer