Reputation: 55
First things first, I am a novice when it comes to Java. I have set myself a little project and I am currently stuck. I am trying to write to a file that already exists, but it just overwrites it. I am trying to replace the line that contains 'maxBooks'.
Here is the code than I am using:
FileWriter writeFile = new FileWriter(fileLocation);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
BufferedWriter writeLines = new BufferedWriter(writeFile);
System.out.println("\n-----File Begin-----");
while((finalLines = readLines.readLine()) != null){
if(finalLines.contains("maxBooks")){
writeLines.newLine();
writeLines.write(finalLines);
System.out.println("This is the if statement");
System.out.println(finalLines);
} else {
fileLines.add(new String(finalLines));
System.out.println("This is the else statement");
System.out.println(finalLines);
}
}
System.out.println("------File End------");
Please bear in mind that I have left out the try and catch. Please let me know how I can edit the text file. Let me know if you need any more info
Thanks :)
EDIT
Sorry, I should clarify. I am just trying to edit 1 line that is in the test file, not the whole text file.
FINAL CODE:
FileWriter writeFile = new FileWriter(fileLocation + ".tmp", true);
BufferedWriter writeLines = new BufferedWriter(writeFile);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
System.out.println("\n-----File Begin-----");
while((finalLines = readLines.readLine()) != null){
if(finalLines.contains("maxBooks")){
writeLines.write("maxBooks = " + maxBooks);
writeLines.newLine();
System.out.println("This is the if statement");
System.out.println(finalLines);
} else {
fileLines.add(new String(finalLines));
System.out.println("This is the else statement");
writeLines.write(finalLines);
writeLines.newLine();
}
}
System.out.println("------File End------");
file2.renameTo(file);
writeLines.close();
Upvotes: 1
Views: 318
Reputation: 1434
you read and write on the same fileLocation
you're supposed to give two differend locations;
goes something like this
//define newLocation as string that contain path for new file to be written
FileWriter writeFile = new FileWriter(newLocation);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
BufferedWriter writeLines = new BufferedWriter(writeFile);
Upvotes: 0
Reputation: 121830
You overwrite the file you try to read, which is bad practice. Write to a new file, then rename to the original file.
Upvotes: 3