Why is this piece of code not working?

I wrote this piece of code, and it should replace all the characters in the file named "abc.txt" with asterisks. But when I run this code, it just erases everything in the file. Please 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();
    }
}
+4
source share
4 answers

You must create files and file readers sequentially, not immediately.

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 the 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();
}
+5
source

First you need to read the file, and then close the file. Then start writing content to it.

By default, it opens the file in recording mode. All data is lost before you read anything.

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

. , FileWriter , .

If you want to add data instead, use:

new FileWriter(theFile, true);
+1
source

As previously reported, you format the file when creating FileWriter, but there is also no reason for you to read the file.

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

Source: https://habr.com/ru/post/1623557/


All Articles