首页 > 解决方案 > 在 Java 中更新 RandomAccessFile 中的数据

问题描述

我的代码有问题,我正在尝试更改给定 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);//this functions writes the bytes of an given string
            }
        }
        
        file.delete();
        temp.renameTo(file);
     
    }
    

所以,为了在 RAF 中写入,我有这个功能,我在文件中写入的所有信息都是 ArrayList<ArrayList>,(这部分很重要)......为此,我有一个看起来相似的版本以下方法

public void wbyte(RandomAccessFile file,String str) throws IOException{
        byte[] byt=str.getBytes();
        for(byte byteWrite : byt){
            file.writeByte(byteWrite);
        }
        file.writeUTF("\n");
        
    }

一切都很好,直到我发现文件的最后一行仍然有一些信息(重复信息)。这是更新前的示例:更新前

而且更新后更新后

如果你看到,它就像垃圾一样。任何帮助将不胜感激:) PS:如果您需要更多代码,请告诉我,但这几乎是我在文件中写入的全部内容

标签: javafilearraylistrandomaccessfile

解决方案


推荐阅读