-
题目:
定义一个集合用于存储多个字符串,向其中添加一些字符串。
然后将集合的所有字符串内容写到文件中。要求每个字符串独占一行。 -
1.定义一个集合ArrayList
2.用来存储多个字符串,泛型就是
3.使用添加字符串到集合中:add
4.既然需要写文件:FileWriter、BufferedWriter。
5.BufferedWriter性能更高
6.集合当中的每一个字符串都要逐一处理:for循环遍历集合
7.在循环当中将字符串写到文件里:调用write方法
8.要求字符串独占一行:调用newLine方法
9.最后不要忘记关闭流
public class FromListToFile {
public static void main(String[] args) throws IOException {
ArrayList<String> ar1 = new ArrayList<>();
ar1.add("Hello");
ar1.add("World");
ar1.add("Java");
System.out.println(ar1); //[Hello, World, Java]
FileWriter fw = new FileWriter("file12.txt");
BufferedWriter bw = new BufferedWriter(fw);
//集合遍历
for(int i = 0 ;i<ar1.size();i++) {
String str = ar1.get(i);
bw.write(str);
bw.newLine();
}
bw.close();
}
}