我是新手,在Java中,我有一个在txt文件上写信息的程序,我似乎唯一的问题是,如果fileWriter追加了我无法编辑的文件,或在文件上重写了特定行,有什么方法可以将writer设置为在文件的开头而不是结尾而不删除数据?因为那样我无法编辑文件中的信息。
预先感谢您的任何回答!

最佳答案

FileWriter类具有几个构造函数。其中一些带有类型为boolean的“ append”参数。您是否在true中使用了这些构造函数之一?

您应该对该参数使用false

    /**
 * Constructs a FileWriter object given a File object. If the second
 * argument is <code>true</code>, then bytes will be written to the end
 * of the file rather than the beginning.
 *
 * @param file  a File object to write to
 * @param     append    if <code>true</code>, then bytes will be written
 *                      to the end of the file rather than the beginning
 * @throws IOException  if the file exists but is a directory rather than
 *                  a regular file, does not exist but cannot be created,
 *                  or cannot be opened for any other reason
 * @since 1.4
 */
public FileWriter(File file, boolean append) throws IOException {
    super(new FileOutputStream(file, append));
}

关于java - 用fileWriter重写一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17472391/

10-10 00:58