为什么这段代码无法运行?

4

我写了这段代码,它应该将文件名为 "abc.txt" 的文件中的所有字符替换为星号。但是当我运行这段代码时,它只是删除了文件中的所有内容。请有人帮我找出问题在哪里。谢谢。

import java.io.*;
import java.util.*;

class Virus{

    public static void main(String[] args) throws Exception{

        File f = new File("abc.txt");
        FileReader fr = new FileReader(f);
        FileWriter fw = new FileWriter(f);
        int count = 0;
        while(fr.read()!=-1){
            count++;
        }
        while(count-->0){
            fw.write('*');
        }
        fw.flush();     
        fr.close();
        fw.close();
    }
}
4个回答

5

您应该按顺序创建文件读取器和写入器,而不是一次性创建。

FileReader fr = new FileReader(f);
FileWriter fw = new FileWriter(f); // here you are deleting your file content before you had chance to read from it

你应该按照以下方式进行操作:
public static void main(String[] args) throws Exception{

    File f = new File("abc.txt");
    FileReader fr = new FileReader(f);
    int count = 0;
    while(fr.read()!=-1){
        count++;
    }
    fr.close();

    FileWriter fw = new FileWriter(f);
    while(count-->0){
        fw.write('*');
    }
    fw.flush();     
    fw.close();
}

但是先生,我不明白为什么创建FileWriter会删除内容? :/ - Rishabh Gour
1
这是打开文件的默认模式,如果文件存在则截断文件。 - UtsavShah
2
因为FileWriter会清除文件,如果文件已经存在,则准备写入内容。还有另一个构造函数告诉FileWriter打开文件以进行追加。 - Dalija Prasnikar

4

首先,您需要读取文件并关闭文件对象。然后开始将内容写入其中。

默认情况下,它以写入模式打开文件。在从中读取任何内容之前,所有数据都会丢失。

class Virus{

  public static void main(String[] args) throws Exception{

    File f = new File("/Users/abafna/coding/src/abc.txt");
    FileReader fr = new FileReader(f);
    int count = 0;
    while(fr.read()!=-1){
      count++;
    }
    fr.close();
    System.out.println(count);
    FileWriter fw = new FileWriter(f);
    while(count-->0){
      fw.write('*');
    }
    fw.flush();
    fw.close();
  }
}

1
Using FileWriter fw = new FileWriter(f);

这将清除您的文件内容。这是因为您正在使用的FileWriter构造函数会截断文件(如果已经存在)。 如果您想要追加数据,请使用:
new FileWriter(theFile, true);

1
正如其他人所说,当您创建FileWriter时,您正在格式化文件,但是您也没有必要读取该文件。
public static void main(String[] args) throws Exception {
    File f = new File("abc.txt");
    long length = f.length(); //length of file. no need to read it.
    OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
    for (int i = 0; i < length; i++) {
        out.write('*');
    }
    out.close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接