Reputation: 170
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();
}
}
Upvotes: 4
Views: 108
Reputation: 418
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();
}
Upvotes: 1
Reputation: 3740
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);
Upvotes: 1
Reputation: 13402
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();
}
}
Upvotes: 4
Reputation: 28516
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();
}
Upvotes: 5