Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this piece of code does not work?

Tags:

java

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();
    }
}
like image 911
Rishabh Gour Avatar asked Dec 18 '22 20:12

Rishabh Gour


1 Answers

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();
}
like image 80
Dalija Prasnikar Avatar answered Dec 21 '22 09:12

Dalija Prasnikar