Java 示例 - 写入文件
-
问题描述
如何写入文件? -
解决方案
此示例显示如何使用 BufferedWriter 的 write 方法写入文件。import java.io.*; public class Main { public static void main(String[] args) { try { BufferedWriter out = new BufferedWriter(new FileWriter("outfilename")); out.write("aString"); out.close(); System.out.println("File created successfully"); } catch (IOException e) { } } }
-
结果
上面的代码示例将产生以下结果。File created successfully.
下面是另一个在java中写入文件的例子import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileExample { public static void main(String[] args) { try { String content = "TutorialsPoint is one the best site in the world"; File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }
上面的代码示例将产生以下结果。Done