以前只知道将对象写入文件用outPutStream,将文件读入到内存用inputStream,但是不知道为什么,今天有人讲解后终于知道了为什么,所以写到这里和大家分享,希望大家以后也不会弄混。
outputstream:是将对象从内存写入到外部,相当于输出,所以用write()。
inputstream:是将外部内容读入到内存,所以是read()。
写的一个demo如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestFile {
public static void main(String[] args) {
new TestFile().writeObject();
new TestFile().readObject();
}
public void writeObject() {
FileOutputStream out;
ObjectOutputStream objectOut = null;
try {
out = new FileOutputStream("D:/testFile.txt");
objectOut = new ObjectOutputStream(out);
} catch (Exception e) {
e.printStackTrace();
}
List<Map<String, Object>> customers = new ArrayList<>();
Map<String,Object> showMessage = new HashMap<>();
showMessage.put("customer", "fiona");
showMessage.put("waitTime", 14);
Map<String,Object> showMessage2 = new HashMap<>();
showMessage2.put("customer", "peter");
showMessage2.put("waitTime", 15);
customers.add(showMessage);
customers.add(showMessage2);
try {
objectOut.writeObject(customers);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void readObject() {
List<Map<String, Object>> customers = null;
FileInputStream in;
ObjectInputStream objectIn = null;
try {
in = new FileInputStream("D:/testFile.txt");
objectIn = new ObjectInputStream(in);
} catch (Exception e) {
e.printStackTrace();
}
try {
customers = (List<Map<String, Object>>) objectIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for(Map<String,Object> map:customers)
{
for(String key : map.keySet()){
System.out.println(key+":"+map.get(key));
}
}
}
}
打印结果:
customer:fiona
waitTime:14
customer:peter
waitTime:15