简体   繁体   中英

Why this piece of code does not work?

I wrote this piece of code and it is supposed to replace all the characters in a file named "abc.txt" with asterisks. But when I run this code it simply erases everything in the file. Please anyone help me figure out what is wrong here. Thanks

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();
    }
}

You should create file reader and writer in sequence, not at once.

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

You should do following:

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();
}

First you need to the reading of the file and then close the file object. Then start writing the content into it.

By default, it opens the file in write mode. All the data is lost before you reading anything from it.

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();
  }
}
Using FileWriter fw = new FileWriter(f);

This clears the content of your file. This is because the constructor of FileWriter you are using truncates the file if it already exists.

If you want to append the data instead, use:

new FileWriter(theFile, true);

As the others have said you are formatting the file when you create a FileWriter, but there is also no reason for you to read the file anyways.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM