知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

    • 扩展

    • IO & Stream

      • Theory:Files
      • Theory:Write files
        • The FileWriter class
        • Closing a FileWriter
        • The PrintWriter class
        • Conclusion
      • Theory:What are streams
      • Theory:Input streams
      • Theory:Try with resources
    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • IO & Stream
Jim
2022-08-12
目录

Theory:Write files

Now that we've learned how to create and manage files, let's discuss how to write text to a file. Java provides different ways for doing it, and in this lesson, we will consider two of the simplest ways: using the java.io.FileWriter and the java.io.PrintWriter classes.

# The FileWriter class

The class FileWriter has a set of constructors to write characters and strings to a specified file:

  • FileWriter(String fileName);
  • FileWriter(String fileName, boolean append);
  • FileWriter(File file);
  • FileWriter(File file, boolean append);

Two constructors take an additional parameter append that indicates whether to append (true) or overwrite (false) an existing file.

All these constructors can throw an IOException for several reasons:

  • if the named file exists but it is a directory;
  • if a file does not exist and cannot be created;
  • if a file exists but cannot be opened.

In this lesson, sometimes we will skip the exception handling mechanism to simplify our examples.

Let's consider the following code:

File file = new File("/home/username/path/to/your/file.txt");
FileWriter writer = new FileWriter(file); // overwrites the file

writer.write("Hello");
writer.write("Java");

writer.close();
1
2
3
4
5
6
7

If the specified file does not exist, it will be created after executing this code. If the file already exists, this code overwrites the data.

The file will contain the text HelloJava.

If you want to append some new data, you should specify the second argument as true.

File file = new File("/home/username/path/to/your/file.txt");
FileWriter writer = new FileWriter(file, true); // appends text to the file

writer.write("Hello, World\n");
writer.close();
1
2
3
4
5

This code appends a new line to the file. Run it multiple times to see what happens. Note that here we are using Unix-like OS line breaks. There is a difference between line break characters on different platforms:

  • \n Unix-like OS
  • \r\n Windows OS

# Closing a FileWriter

It is important to close a FileWriter after using it to avoid a resource leak. This is done by invoking the close method:

writer.close();
1

Since Java 7, a convenient way to close an object of FileWriter is to use the try-with-resources statement.

File file = new File("/home/username/path/to/your/file.txt");

try (FileWriter writer = new FileWriter(file)) {
    writer.write("Hello, World");
} catch (IOException e) {
    System.out.printf("An exception occurred %s", e.getMessage());
}
1
2
3
4
5
6
7

It will close the writer automatically.

# The PrintWriter class

The PrintWriter class allows you to write formatted data to a file. It can output strings, primitive types and even an array of characters. The class provides several overloaded methods: print, println and printf.

File file = new File("/home/art/Documents/file.txt");
try (PrintWriter printWriter = new PrintWriter(file)) {
    printWriter.print("Hello"); // prints a string
    printWriter.println("Java"); // prints a string and then terminates the line
    printWriter.println(123); // prints a number
    printWriter.printf("You have %d %s", 400, "gold coins"); // prints a formatted string
} catch (IOException e) {
    System.out.printf("An exception occurred %s", e.getMessage());
}
1
2
3
4
5
6
7
8
9

This example first creates an instance of File and, second, a PrintWriter in the try-with-resources statement to close it correctly. It writes "Hello"and "Java" on the same line, and then 123 on a new line. This example also calls the advanced printf method which can format a text using %d, %s and so on. Finally, the PrintWriter is closed.

The result contains:

HelloJava
123
You have 400 gold coins
1
2
3

The class has several constructors. Some of them are similar to FileWriter's constructors:

  • PrintWriter(String fileName);
  • PrintWriter(File file).

Others allow to pass FileWriter as a class that extends the Writer abstract class:

  • PrintWriter(Writer writer).

# Conclusion

FileWriter and PrintWriter both extend the Writer abstract class and have many similarities. However, PrintWriter is more of a high-level one and provides several useful methods. Among them are formatting methods and overloaded print methods for writing primitive types.

编辑 (opens new window)
#I/O#Java
上次更新: 2022/09/26, 16:55:15
Theory:Files
Theory:What are streams

← Theory:Files Theory:What are streams→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式