Let's say I have the following code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( br.readLine() != null ){
verify = br.readLine();
if(verify != null){
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".
I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.
use this code, I used it to remove logs and System.out statements in java file. just change the matching and replacing string.
I would do it this way:
There is no need to type
bw.write(putData);
, because it will just print the statement twice.Whatever you want in a file, just give the correct path of the file and use the above code accordingly.
Change your code to that:
The Problem is that you are calling
br.readLine()
twice which is provoking the application to read line1 and then line2 and in your case you have just one line which means that your program read it in the conditional form and when it comes to declaring it to the variableverify
, it is stopping because you don't have anymore data to read your file.