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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With