java新建文件并写入的几种方式
因为涉及到文件流,我们在新建完一个流之后需要关闭他,即close()。这里使用try-with-resources语法,流会自动关闭
-
java8 Files.newBufferedWriter()
java8提供的newBufferedWriter(),既可以创建文件,也可以通过设置参数来完成追加写
@Test void testCreateFile1() throws IOException { String filename = "D:\\playground\\test\\newFile.txt"; Path path = Paths.get(filename); //使用newBufferedWriter创建文件并写入文件 //使用try无需手动关闭 try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { writer.write("Hello World!! 创建文件"); } //追加写模式 try(BufferedWriter writer = Files.newBufferedWriter(path,StandardCharsets.UTF_8, StandardOpenOption.APPEND)){ writer.append("追加写"); } }
-
Files.write
不需要使用流,通过Files.write()直接传递路径内容以及格式。
@Test void testCreateFile2() throws IOException { String filename = "D:\\playground\\test\\newFile2.txt"; //JDK1.7开始的方法 //不需要使用流 只需要通过Files的write传递文件的路径,内容以及格式 Files.write(Paths.get(filename),"Hello World!! 创建文件".getBytes(StandardCharsets.UTF_8)); //追加写模式 Files.write(Paths.get(filename),"追加写".getBytes(StandardCharsets.UTF_8),StandardOpenOption.APPEND); }
-
PrintWriter
java老版本中的一种写文件的方式,是通过println写入的,因此可以做到一行一行写入,在java10中增加了字符集参数。
@Test void testCreateFiles3() throws FileNotFoundException, UnsupportedEncodingException { //jdk5 PrintWriter String filename = "D:\\playground\\test\\newFile3.txt"; try (PrintWriter printWriter = new PrintWriter(filename,"utf-8")){ //一行一行写 printWriter.println("Hello World"); printWriter.println("追加写"); } }
-
管道流
管道流虽然原始,但因为是分步骤的,所以定制化比较高
@Test void testCreateFiles5() throws IOException { String filename = "D:\\playground\\test\\newFile4.txt"; try (FileOutputStream fos = new FileOutputStream(filename); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw)){ bw.write("Hello World"); bw.flush(); } }
这里我总结了这四种,当然真正写文件的方式远远不止这四种,这里仅仅是学习总结。
这四种推荐第二种,不仅书写简单,而且底层是通过NIO实现的,简单高效。