英文:
Update Data in a RandomAccessFile in Java
问题
我在我的代码中遇到了一个问题,我正在尝试更改给定的RandomAccessFile和一个对象的数据,更确切地说,是删除该出现的部分。以下是第一部分:
public void updateData(File file, InfoPlayers player) throws FileNotFoundException, IOException {
File temp = File.createTempFile("file", ".txt", file.getParentFile());
RandomAccessFile f = new RandomAccessFile(file, "rw");
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
for (String line; (line = reader.readLine()) != null;) {
if (!line.contains(player.getMail())) {
System.out.println("line" + line);
wbyte(f, line); // 这个函数将给定字符串的字节写入
}
}
file.delete();
temp.renameTo(file);
}
为了写入RAF,我有这个函数,我在文件中写入的所有信息都是ArrayList<ArrayList<String>>(这部分很重要)......为了做到这一点,我有了一个类似的版本以下面的方法:
public void wbyte(RandomAccessFile file, String str) throws IOException {
byte[] byt = str.getBytes();
for (byte byteWrite : byt) {
file.writeByte(byteWrite);
}
file.writeUTF("\n");
}
一切都很好,直到我发现文件的最后一行仍然有一些信息(重复的信息)。以下是更新之前的示例:
以及更新之后的情况:
如果你看到,就像是垃圾。任何帮助将不胜感激
附注:如果你需要更多的代码,只需告诉我,但这几乎是我用来写入文件的全部内容。
英文:
I have a problem with my code, I'm trying to change the data of a given RandomAccessFile and an Object, it's more about deleting that occurrence. Here's the first part:
public void updateData(File file,InfoPlayers player) throws FileNotFoundException, IOException {
File temp = File.createTempFile("file", ".txt", file.getParentFile());
RandomAccessFile f= new RandomAccessFile(file,"rw");
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
for (String line; (line = reader.readLine()) != null;){
if(!line.contains(player.getMail())){
System.out.println("line"+line);
wbyte(f, line);//this functions writes the bytes of an given string
}
}
file.delete();
temp.renameTo(file);
}
So, in order to write in the RAF I have this function, all the info that i write in the files are ArrayList<ArrayList<String>>, (this part is important)... to do so, i have a look alike version of the following method
public void wbyte(RandomAccessFile file,String str) throws IOException{
byte[] byt=str.getBytes();
for(byte byteWrite : byt){
file.writeByte(byteWrite);
}
file.writeUTF("\n");
}
Everything's fine, until I found out that the last line of the file still has some info (repeated info). Here's an example before the update:
And after the updating
If you see, it's like garbage. Any help would be appreciated
PS: If you need more code, just tell me, but this is almost all I use to write in the file
专注分享java语言的经验与见解,让所有开发者获益!
评论