我正在编写一个将数组对象写入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]
答案 0 :(得分:0)
您正在使用null
值初始化声明b。
Datab[] b = null;
然后您无法更新b
最后,您将返回b
,其初始化为null