seek()方法不能与java中的InputStream available()方法一起使用



我正在处理这个java问题,我必须在不回火该文件上现有文本数据的情况下写入系统上的文本文件,我使用randomAceessFile.seek((inputStream.available()+1));将指针指向现有数据前面的1个空间,然后使用randomAceessFile.write((newData.trim()).getBytes());写入该文件,现在的问题是,在该操作之后,文件数据应该在现有数据和添加的新数据之间有空间,但下面的代码只向文件和CCD_ 3添加了新数据,而不是在数据之间添加空格。

import java.io.RandomAccessFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Random{
public static void main(String[] args) {
try {
File file = new File("data.txt");
InputStream inputStream = new FileInputStream(file);
RandomAccessFile randomAceessFile = new RandomAccessFile(file, "rw");
randomAceessFile.seek((inputStream.available()+1));
String newData = "new data on file";
randomAceessFile.write((newData.trim()).getBytes());
randomAceessFile.close();
inputStream.close();
} catch (Exception e) {
System.err.println(e.getCause());
System.out.println(e.getStackTrace());
System.out.println(e.getMessage());
}
}
}

该程序给出的输出是

现有数据\00文件上的新数据

零字节是因为您寻求的是退出长度加一。现有的字节编号为0到长度-1,因此您希望精确地查找现有的长度。

也就是说,在偏移量为"现有长度"的情况下,没有任何内容专门写入到文件中,因此您得到一个零字节。

没有人会神奇地插入以前没有的空间(0x20字节(。你需要这样做。这很简单:newData = " new data on file"(并省略对你所写内容的trim调用(。

也许你之前读到的是在"位置"的意义上使用"空间"这个词?

最新更新