[Java] 纯文本查看 复制代码
/*已知集合ArrayList中有, ”张三丰”,”景甜”,”林思意”,”鹿晗”;
把集合中人名写入当前项目的根目录下的names.txt中,每一个人名占一行;
要求: 使用try...catch...finally对异常进行处理*/
public class Test {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<>();
array.add("张三丰");
array.add("景甜");
array.add("林思意");
array.add("鹿晗");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("names.txt"));
for (int i = 0; i < array.size(); i++) {
bw.write(array.get(i));
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}