如何将ArrayList存储的对象使用io流输出到txt文件中,并解决乱码问题
时间: 2024-02-10 13:11:02 浏览: 36
如果要将ArrayList存储的对象输出到txt文件中,并解决乱码问题,可以使用Java中的ObjectOutputStream和FileOutputStream来实现将ArrayList对象集合输出到txt文件中。同时,还需要使用OutputStreamWriter和FileWriter将字节流转换成字符流,并指定字符编码格式。具体步骤如下:
1. 创建一个FileOutputStream对象,指定要输出的txt文件路径,例如:FileOutputStream fos = new FileOutputStream("output.txt");
2. 创建一个ObjectOutputStream对象,将FileOutputStream对象传入其中,例如:ObjectOutputStream oos = new ObjectOutputStream(fos);
3. 将ArrayList对象集合写入ObjectOutputStream对象中,例如:oos.writeObject(list);
4. 创建一个OutputStreamWriter对象,将FileOutputStream对象传入其中,同时指定字符编码格式,例如:OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
5. 创建一个BufferedWriter对象,将OutputStreamWriter对象传入其中,例如:BufferedWriter bw = new BufferedWriter(osw);
6. 将ArrayList对象集合转换成字符串格式,并写入BufferedWriter对象中,例如:
```
for (Person person : list) {
String str = person.toString();
bw.write(str);
bw.newLine();
}
```
7. 最后记得关闭BufferedWriter、OutputStreamWriter、ObjectOutputStream和FileOutputStream对象,释放资源,例如:bw.close(); osw.close(); oos.close(); fos.close();。
完整代码示例:
```
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
public class ArrayListToFile {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<Person>();
list.add(new Person("Tom", 18));
list.add(new Person("Jerry", 20));
list.add(new Person("Alice", 22));
try {
FileOutputStream fos = new FileOutputStream("output.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
for (Person person : list) {
String str = person.toString();
bw.write(str);
bw.newLine();
}
bw.close();
osw.close();
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 省略getter和setter方法
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
```
注意:要将存储的对象实现Serializable接口,以便序列化和反序列化。此外,如果存储的对象是自定义的类,需要重写toString方法,将其转换成字符串格式。