0
我正在編寫一個程序,將一個數組對象寫入一個java二進制文件,然後將其讀回。問題是當數組讀入數組時,它正在返回[null,null ]。我沒有正確地讀/寫對象嗎?對象無法正常讀取
DBMS.java
public static void writeToFile(Datab[] friends) {
try {
ObjectOutputStream myStream = new ObjectOutputStream(
new FileOutputStream("datt.dat"));
for(int i=0; i<friends.length; i++){
myStream.writeObject(friends[i]);
}
myStream.close();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
System.out.println("\n\nArray written to file datt.");
}
/**********************************************************
* readFromFile Read from the binary file and return the array of objects to
* the calling method Catch the following exceptions: FileNotFoundException,
* ClassNotFoundException, and the IOException (know what each does!)
*
* @return The array as read in from the binary input file
*/
public static Datab[] readFromFile() {
System.out
.println("\n\nNow let's reopen the file and display the array.");
Datab[] b = null;
// The name of the file to open.
String fileName = "datt.dat";
try {
// Use this for reading the data.
byte[] buffer = new byte[1000];
ObjectInputStream input = new ObjectInputStream(new FileInputStream("datt.dat"));
input.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
return b;
}
輸出:
[Robert , Duchar 7345555555, Len , Gt 7345555567]
陣列寫入文件達特:將其寫入到輸出文件中之前 陣列。
現在讓我們重新打開文件並顯示數組。
從輸入文件中讀入的數組... 您想查看數組的向後還是向前? 輸入你的答案(B或F):F
[null, null]
您創建一個InputStream,但實際上並沒有讀什麼。 – DennisW 2015-04-01 05:53:09
您確實讀取了InputStream,但未保存在任何數組中。預計b [i] = input.Something – Sarz 2015-04-01 05:57:50