36 Java 文件流操作基础

36 Java 文件流操作基础

在Java中,文件流用于读写文件。我们可以通过InputStreamOutputStream类来处理字节流,还可以通过ReaderWriter类来处理字符流。本节将详细介绍如何进行文件的基本操作。

1. 文件的概念

在计算机中,文件是用于存储数据的基本单位。Java提供了多种方法来读取和写入文件数据。

2. 文件流的分类

  • 字节流:用于处理原始二进制数据,适合读取和写入任何类型的文件。

    • 输入字节流: InputStream
    • 输出字节流: OutputStream
  • 字符流:用于处理字符数据,适合处理文本文件。

    • 输入字符流: Reader
    • 输出字符流: Writer

3. 字节流操作示例

3.1 使用字节输入流读取文件

我们可以使用FileInputStream类来读取文件。以下是一个简单的读取文件内容的示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.io.FileInputStream;
import java.io.IOException;

public class FileReadExample {
public static void main(String[] args) {
String filePath = "example.txt"; // 文件路径
FileInputStream fis = null;

try {
fis = new FileInputStream(filePath);
int data;

// 逐字节读取文件
while ((data = fis.read()) != -1) {
// 输出字节,转换为字符
System.out.print((char) data);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close(); // 关闭输入流
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

3.2 使用字节输出流写入文件

使用FileOutputStream类可以将数据写入文件。下面的示例展示如何将字符串写入文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriteExample {
public static void main(String[] args) {
String filePath = "output.txt"; // 输出文件路径
FileOutputStream fos = null;

try {
fos = new FileOutputStream(filePath);
String data = "Hello, Java File IO!";

// 将字符串转换为字节数组
fos.write(data.getBytes());

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close(); // 关闭输出流
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

4. 字符流操作示例

4.1 使用字符输入流读取文件

我们可以使用FileReader类来读取文本文件。以下是一个读取文本文件内容的示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class CharFileReadExample {
public static void main(String[] args) {
String filePath = "example.txt"; // 文件路径

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;

// 逐行读取文件
while ((line = br.readLine()) != null) {
System.out.println(line);
}

} catch (IOException e) {
e.printStackTrace();
}
}
}

4.2 使用字符输出流写入文件

使用FileWriter类可以将字符串写入文本文件。下面的示例将字符串写入文本文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.FileWriter;
import java.io.IOException;

public class CharFileWriteExample {
public static void main(String[] args) {
String filePath = "output.txt"; // 输出文件路径

try (FileWriter fw = new FileWriter(filePath)) {
String data = "Hello, Java File IO using Writer!";

fw.write(data);

} catch (IOException e) {
e.printStackTrace();
}
}
}

5. 小结

通过以上示例,我们学习了如何使用Java的文件流进行基本的文件读写操作。记住使用try-with-resources语句来确保流的正确关闭。同时,根据文件内容的性质选择合适的流(字节流或字符流)。掌握这些基本的文件流操作后,你就可以灵活地处理文件数据了。

36 Java 文件流操作基础

https://zglg.work/java-zero/36/

作者

AI教程网

发布于

2024-08-08

更新于

2024-08-10

许可协议