Java文件写入操作全解析
立即解锁
发布时间: 2025-08-18 02:26:24 阅读量: 2 订阅数: 18 

### Java 文件写入操作全解析
#### 1. 文件位置操作
在 Java 中,`FileChannel` 对象提供了两个版本的 `position()` 方法。无参数的 `position()` 方法返回文件的当前位置,类型为 `long`,这是为了支持可能包含超过二十亿字节的大文件。你也可以通过传入一个 `long` 类型的参数来调用 `position()` 方法,从而设置文件的新位置。
以下是一个示例代码,展示如何将文件位置向后移动 100 字节:
```java
try {
outputChannel.position(fileChannel.position() – 100L);
} catch (IOException e) {
e.printStackTrace();
}
```
需要注意的是,调用 `position()` 方法时通常应放在 `try` 块中,因为如果发生 I/O 错误,它可能会抛出 `IOException` 异常。此外,你可以将文件位置设置到文件末尾之后。如果之后向文件写入数据,文件之前的末尾和新位置之间的字节将包含垃圾值。如果尝试从文件末尾之后的位置读取数据,将立即返回文件结束条件。
#### 2. 使用视图缓冲区加载字节缓冲区
除了之前示例中的方法,还可以使用视图缓冲区将字符串写入缓冲区。以下是示例代码:
```java
ByteBuffer buf = ByteBuffer.allocate(1024);
CharBuffer charBuf = buf.asCharBuffer();
charBuf.put(phrase); // Transfer string to buffer
buf.limit(2*charBuf.position()); // Update the byte buffer limit
```
通过 `CharBuffer` 类型的视图缓冲区传输字符串更加简单。但需要注意的是,底层的 `ByteBuffer` 并不知道你放入视图缓冲区的任何数据。`buf` 的位置仍然为零,限制设置为容量,因此翻转它并不会使其准备好写入通道。你只需要将 `buf` 的限制设置为与传输到视图缓冲区的字节数相对应即可。
#### 3. 向文件写入不同长度的字符串
在很多情况下,你可能需要使用通道向文件写入不同长度的字符串。如果要从文件中恢复这些字符串,就需要在文件中提供一些信息,以便确定每个字符串的开头和/或结尾。一种方法是在每个字符串之前立即写入该字符串的长度,这样在读取字符串之前就可以知道其中有多少个字符。
以下是一个示例代码,展示如何向文件写入多个字符串:
```java
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.util.EnumSet;
import java.io.IOException;
import java.nio.ByteBuffer;
public class WriteProverbs {
public static void main(String[] args) {
String[] sayings = {
"Indecision maximizes flexibility.",
"Only the mediocre are always at their best.",
"A little knowledge is a dangerous thing.",
"Many a mickle makes a muckle.",
"Who begins too much achieves little.",
"Who knows most says least.",
"A wise man sits on the hole in his carpet."
};
Path file = Paths.get(System.getProperty("user.home"))
.resolve("Beginning Java Stuff").resolve("Proverbs.txt");
try {
// Make sure we have the directory
Files.createDirectories(file.getParent());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("New file is: " + file);
// The buffer must accommodate the longest string
int maxLength = 0;
for (String saying : sayings) {
if(maxLength < saying.length())
maxLength = saying.length();
}
// The buffer length must hold the longest string
// plus its length as a binary integer
ByteBuffer buf = ByteBuffer.allocate(2*maxLength + 4);
try (WritableByteChannel channel = Files.newByteChannel(
file, EnumSet.of(WRITE, CREATE, APPEND))) {
for (String saying : sayings) {
buf.putInt(saying.length()).asCharBuffer().put(saying);
buf.position(buf.position() + 2*saying.length()).flip();
channel.write(buf); // Write the buffer to the file channel
buf.clear();
}
System.out.println("Proverbs written to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该程序的工作流程如下:
1. 创建一个包含七个谚语的字符串数组 `sayings[]`。
2. 找到最长字符串的长度,并据此分配一个足够大的 `ByteBuffer` 对象。
3. 在 `for` 循环中,将每个谚语的长度和内容写入缓冲区,然后将缓冲区的内容写入文件通道。
4. 每次写入后,调用 `clear()` 方法重置缓冲区的位置和限制,以便为下一个谚语的写入做好准备。
#### 4. 使用格式化器对象加载缓冲区
`java.util.Formatter` 类提供了一个构造函数,它接受一个 `java.lang.Appendable` 类型的引用作为参数。由于 `PrintStream` 和 `PrintWriter` 类实现了 `Appendable` 接口,因此可以构造一个 `Formatter` 对象,将数据格式化到这些对象中。`CharBuffer` 类也实现了 `Appendable` 接口,所以可以创建一个 `Formatter` 对象,将数据格式化到 `CharBuffer` 类型的视图缓冲区中。
以下是一个示例代码,展示如何使用 `Formatter` 对象准备要写入文件的数据:
```java
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.WritableByteChannel;
import java.nio.*;
import java.util.*;
import java.io.IOException;
public class UsingAFormatter {
public static void main(String[] args) {
String[] phrases = {
"Rome wasn’t burned in a day.",
"It’s a bold mouse that sits in the c
```
0
0
复制全文
相关推荐










