文件内容:
/** * 将 list 写入文件中 */ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.filechooser.FileSystemView; public class writeListToFile { public static void main(String[] args) { FileSystemView fsv = FileSystemView.getFileSystemView(); File com = fsv.getHomeDirectory(); String deskPath = com.getPath(); System.out.println( deskPath ); File file = new File( deskPath + "\\" + "aa.txt" ); List<String> list = new ArrayList<String>(); list.add( "123" ); list.add( "second" ); list.add( "third" ); BufferedWriter bw = null; try { bw = new BufferedWriter( new FileWriter(file) ); for(int i = 0; i < list.size(); i++ ) { bw.write( list.get(i) ); bw.newLine(); } bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
进入桌面,打开 aa.txt 文档,如下图: