Java reads and writes files mainly using classes in the java.io package. Commonly used classes include: 1. File: used to represent the path name of a file or directory; 2. FileReader and FileWriter: used to read and write character streams; 3. BufferedReader and BufferedWriter: provide buffering functions for more efficient reading. Write files; 4. FileInputStream and FileOutputStream: used to read and write byte streams, etc.
Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In Java, reading and writing files mainly uses classes in the java.io package. Commonly used classes include:
#File: used to represent the path name of a file or directory.
FileReader and FileWriter: used to read and write character streams.
BufferedReader and BufferedWriter: Provide buffering functions to read and write files more efficiently.
FileInputStream and FileOutputStream: used to read and write byte streams.
InputStreamReader and OutputStreamWriter: used to convert between character streams and byte streams.
Here is a simple example demonstrating how to use these classes to read and write files:
java
import java.io.*; public class FileExample { public static void main(String[] args) { try { // 创建文件对象 File file = new File("example.txt"); // 创建文件读取器 FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); // 读取文件内容并输出到控制台 String line; while ((line = br.readLine()) != null) { System.out.println(line); } // 关闭文件读取器 br.close(); // 创建文件写入器 FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); // 写入文件内容 bw.write("Hello World!"); // 关闭文件写入器 bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
The above is the detailed content of What class does java use to read and write files?. For more information, please follow other related articles on the PHP Chinese website!