更新時(shí)間:2022-07-28 11:38:38 來源:動(dòng)力節(jié)點(diǎn) 瀏覽2557次
Java保存文件到桌面的代碼是什么?動(dòng)力節(jié)點(diǎn)小編來告訴大家。
import javax.swing.filechooser.FileSystemView;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
/**
* @date 2021/3/15 8:56
*/
public class AutoTest {
public static void main(String[] args) throws IOException {
//創(chuàng)建ArrayList集合
ArrayList<Student> array = new ArrayList<Student>();
//創(chuàng)建學(xué)生對象
Student s1 = new Student();
s1.setStuNo("001");
s1.setStuName("張三");
Student s2 = new Student();
s2.setStuNo("002");
s2.setStuName("李四");
Student s3 = new Student();
s3.setStuNo("003");
s3.setStuName("王五");
//把學(xué)生對象添加到集合中
array.add(s1);
array.add(s2);
array.add(s3);
FileSystemView systemView = FileSystemView.getFileSystemView();
File homeDirectory = systemView.getHomeDirectory();
//桌面路徑
String path = homeDirectory.getPath();
System.out.println(path+"-----------------");
//創(chuàng)建字符緩沖輸出流對象
BufferedWriter bw = new BufferedWriter(new FileWriter(path+"\\"+"msg.txt"));
//遍歷集合,得到每一個(gè)學(xué)生對象
for (Student s : array) {
//把學(xué)生對象的數(shù)據(jù)拼接成指定格式的字符串
StringBuilder sb = new StringBuilder();
sb.append(s.getStuNo()).append(",").append(s.getStuName());
//調(diào)用字符緩沖輸出流對象的方法寫數(shù)據(jù)
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
//釋放資源
bw.close();
}
}
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743