问题描述
- 求大神!!!如何把ArrayList集合写入txt文件
-
如何把ArrayList集合写入txt文件 谢谢!!!急用!!!
解决方案
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
public class ArrayToTxt {
public static void main(String[] args) throws Exception{
File f=new File("d:/1.txt");
ArrayList<String> al=new ArrayList<String>();
al.add("first");
al.add("second");
al.add("third");
BufferedWriter bw=new BufferedWriter(new FileWriter(f));
for(int i=0;i<al.size();i++){
bw.write(al.get(i));
bw.newLine();
}
bw.close();
}
}
解决方案二:
缓冲字符(BufferedWriter )是一个字符流类来处理字符数据。不同于字节流(数据转换成字节),你可以直接写字符串,数组或集合保存到文件。
复制代码 代码如下:
package com.yiibai.iofile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/users/mkyong/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
解决方案三:
循环输出,加特殊标记(如换行符)区分对象
解决方案四:
看看我这个文章,java向文件写入数据的3种方式。
http://blog.csdn.net/wgw335363240/article/details/5678965
解决方案五:
public class Test {
public static void main(String[] args) throws IOException {
List list=new ArrayList();
for (int i = 0; i < 10; i++) {
list.add(i);//集合中放入0-9
}
//下面是写文件
boolean flag = false;
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter("d:/test.txt", true);
bw = new BufferedWriter(fw, 100);
for (Integer integer : list) {
bw.write(integer+"");
}
flag = true;
} catch (IOException e) {
System.out.println("写入文件出错");
flag = false;
} finally {
if (bw != null) {
bw.flush();
bw.close();
}
if (fw != null)
fw.close();
}
}
}