Java 写入文件

在下面的示例中,我们使用 FileWriter 类及其 write() 方法将一些文本写入在上面的示例中创建的文件。请注意,当您完成对文件的写入时,应该使用 close() 方法将其关闭。

  1. import java.io.FileWriter;
  2. import java.io.IOException;
  3. public class WriteToFile {
  4. public static void main(String[] args) {
  5. try {
  6. FileWriter myWriter = new FileWriter("filename.txt");
  7. myWriter.write("Files in Java might be tricky, but it is fun enough!");
  8. myWriter.close();
  9. System.out.println("Successfully wrote to the file.");
  10. } catch (IOException e) {
  11. System.out.println("An error occurred.");
  12. e.printStackTrace();
  13. }
  14. }
  15. }

结果如下:

Successfully wrote to the file.

分类导航