java将list写到⽂件_java中将list、map对象写⼊⽂件
java的IO包当中提供了,向⽂件中写⼊⽂件和读取⽂件的⽅法。好吧,来看下具体怎么回事吧。我们先写⼀个像⽂件当中写单个对象的⽅法吧。
public void writeObject() {
try {
HashMap<String,String> map = new HashMap<String,String>();
map.put("name", "foolfish");
FileOutputStream outStream = new FileOutputStream("E:/1.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.writeObject(map);
outStream.close();
System.out.println("successful");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
这⾥我们将⼀个map对象插⼊⼀个txt⽂件当中。java的IO包当中提供了Object的⽂件流。代码很简单,我们下⾯来看⼀看从该⽂件当中读取这个对象吧
public void readObject(){
FileInputStream freader;
try {
freader = new FileInputStream("E:/1.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(freader);
HashMap<String,String> map = new HashMap<String,String>();
map = (HashMap<String, String>) adObject();
System.out.println("The name is " + ("name"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
/
/ TODO Auto-generated catch block
e.printStackTrace();
}
}
代码也很简单,我们使⽤ObjectInputStream 的readobject的就可以读取⽂件中的对象,再按照封装对
象时候的类型进⾏强制转换⼀下。输出结果是aa foolfish。
上⾯提供的是对单个对象的存⼊和读取。对多个不同的对象该⽅法也适⽤。还是⽤代码来说明下吧。我们同时插⼊两个不同的对象,⼀个map,⼀个list。
public class ObjectToFile {
public void writeObject() {
try {
HashMap<String,String> map = new HashMap<String,String>();
map.put("name", "foolfish");
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("everyone");
FileOutputStream outStream = new FileOutputStream("E:/1.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.writeObject(map);
objectOutputStream.writeObject(list);
outStream.close();
System.out.println("successful");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readObject(){
FileInputStream freader;
try {
freader = new FileInputStream("E:/1.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(freader);
HashMap<String,String> map = new HashMap<String,String>(); map = (HashMap<String, String>) adObject(); ArrayList<String> list = new ArrayList<String>();
list = (ArrayList<String>) adObject(); System.out.println("The name is " + ("name"));
System.out.println("aa " + (1));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
generated// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
ObjectToFile of = new ObjectToFile();
of.writeObject();
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论