【问题标题】:Strange behavior of RandomAccessFile objectRandomAccessFile 对象的奇怪行为
【发布时间】:2010-12-06 03:45:27
【问题描述】:

这是一段行为异常的代码。

    private void saveToFile() throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    File name = null;

        int returnVal = fileChooser.showSaveDialog(fileChooser);
    
    //Sets the variable name to the file the user selected.
    if (returnVal == JFileChooser.APPROVE_OPTION) {
             name = fileChooser.getSelectedFile();
        //Exits the method if the user selected cancel in the dialog box.
    }else if (returnVal == JFileChooser.CANCEL_OPTION) {
             return;
        }
    
    //Writes the text data to a file.
    try {
        //Writes the text in the textArea to the file which was selected.
        RandomAccessFile raf = new RandomAccessFile(name, "rw");
        raf.writeBytes(textArea.getText());
        raf.close();
    //Display the stack trace and an error message if the file could not be written.
    } catch (IOException e) {
        e.printStackTrace();
        System.err.print("    Cannot process file....\n");
    }
    
        //Displays the filename of which the file was saved to.
    String fileName = name.getName();
        super.setTitle("XText: " + fileName);
    
    //The text has now been saved and is no longer considered changed.
    changed = false;
}

此代码导致的问题是,当我将已更改的文件保存回自身时,当文件大小小于打开时的大小时,保存的文本与显示的文本不同。我将向您展示所有 3 个文本示例。

打开的文件文本。

现在是所有好人都来援助他们的国家的时候了。
现在是所有好人来援助他们国家的时候了。
现在是所有好人来援助他们国家的时候了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。

改为。

现在是所有好人都来援助他们的国家的时候了。
现在是所有好人来援助他们国家的时候了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。

保存文件中的文本。在另一个编辑器中打开。

现在是所有好人都来援助他们的国家的时候了。
现在是所有好人来援助他们国家的时候了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。

懒狗回来了。
敏捷的棕色狐狸跳过懒狗的背。
敏捷的棕狐跳过了懒狗的背。

如果将文本保存到新文件中,文本会很好地保存。

【问题讨论】:

    标签: java


    【解决方案1】:

    您为什么希望它为您截断?您打开现有文件(例如大小 1000)进行写入,在那里写入(例如)800 个字节 - 大小仍然是 1000,最后 200 个现在包含垃圾!

    如果您想坚持使用随机访问文件,请在打开后立即尝试 file.setLength(0)。

    否则,我建议:

    FileWriter fw = new FileWriter(name);
    fw.write(text);
    fw.close();
    

    【讨论】:

    • 太棒了。这就是我希望我能得到的答案。在我发布我的问题后,我的导师找到了 file.setLength(0) 解决方案。如果我以后使用 RandomAccessFile 对象,我会记得使用 file.setLength(0)。我想知道为什么这个对象的 API 没有说明必须这样做,或者我只是一只眼睛失明,另一只眼睛看不到。感谢您的帮助。
    • API cmets 没有这么说,因为他们认为您使用 RandomAccessFile 是有原因的。因为通常它不是写出文件的首选。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2015-04-20
    • 1970-01-01
    • 2023-01-29
    • 2017-11-07
    • 2023-03-17
    • 2014-02-20
    相关资源
    最近更新 更多