因此,我使用了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