📅  最后修改于: 2023-12-03 15:01:56.407000             🧑  作者: Mango
在Java中,PrintStream类是OutputStream类的子类,它提供了方便的打印输出功能。PrintStream类中提供了许多write()方法,其中write(byte[], int, int)可以写入字节数组的一部分到输出流中。下面我们来详细了解一下该方法的用法。
public void write(byte[] b, int off, int len)
其中,b、off和len的含义与write(byte[])方法相同。使用该方法后,off位置之前的字节不会被写入到输出流中。
该方法没有返回值。
下面我们来看一个示例,实现了使用write(byte[], int, int)方法向文件中追加字节内容的功能。
import java.io.*;
public class AppendBytesToFile {
public static void main(String[] args) {
String filePath = "D:\\test.txt";
String content = "Hello World!";
try {
// 打开文件,追加模式写入
FileOutputStream fos = new FileOutputStream(filePath, true);
PrintStream ps = new PrintStream(fos);
// 将内容转换为字节数组
byte[] bytes = content.getBytes();
// 将字节数组写入输出流
ps.write(bytes, 0, bytes.length);
// 关闭输出流和文件流
ps.close();
fos.close();
System.out.println("内容已追加到文件中。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行该程序后,将在指定路径的文件中追加内容"Hello World!"。 可以使用以下代码查看文件内容:
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
输出内容为:
Hello World!
以上就是PrintStream write(byte[], int, int)方法的详细介绍和示例。