Home>Article>Java> What class does java use to read and write files?

What class does java use to read and write files?

小老鼠
小老鼠 Original
2023-12-27 15:51:58 1153browse

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.

What class does java use to read and write files?

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:

  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 to read and write files more efficiently.

  4. FileInputStream and FileOutputStream: used to read and write byte streams.

  5. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn