尝试使用RandomAcessFile读取和写入同一文件时出现问题。写入字节块后的文件更改权限
我正在从一个文件读取16个字节的块,并将它们写入给定位置(例如256个)的同一个文件中。
问题出在ra.write(b)
一行。当下面一行是执行我上了文本编辑器凯特消息(我使用Linux Manjaro)说:
文件/home/mite/IdeaProjects/IspitJuni2015/dat.txt与打开UTF-8编码但包含无效字符。 它被设置为只读模式,因为保存可能会破坏其内容。 可以选择正确的编码重新打开文件,也可以在工具菜单中再次启用读写模式以编辑它。
它打开只读模式。 另外我尝试手动取消在凯特只读权限,但它也不工作。什么似乎是问题?
public static byte[] read(long i) throws IOException{
File in = new File("./dat.txt");
RandomAccessFile ra = new RandomAccessFile(in,"rw");
byte[] readObj= new byte[16];
if (i>in.length()/16)
{
return null;
}
ra.seek(i*16);
ra.read(readObj);
ra.close();
return readObj;
}
public static void write(long i, byte[] obj) throws IOException{
File out=new File("./dat.txt");
RandomAccessFile ra=new RandomAccessFile(out,"rw");
if (!out.exists())
{
out.createNewFile();
}
long size=out.length();
if (i*16>size)
{
ra.seek(out.length());
for (long j=size;j<i*16;j+=16)
{
byte[] b=new byte[16];
ra.write(b);
}
}
ra.seek((i)*16);
System.out.println(new String(obj));
ra.write(obj);
ra.close();
}
public static void main(String[] args) throws IOException{
write(35,read(4));
}
'out.exists()/ createNewFile()'块在最好情况下毫无意义,但尤其如此*在构建了'RandomAccessFile'之后。去掉它。 – EJP
Hi Mitko。答案已在下面提出,你是否能够回复它,并回答它是否帮助你? – halfer
@halfer嗨,我留下重播和可能的解决方案。你可以看下面的 –