Reputation: 1
The content of Testing.txt
is not getting copied in Testing2.txt
. If I store some random data in Testing2.txt
it gets erased when i run the java project instead of copying the content of Testing.txt
.
Here is the link to the tutorial I am practicing. The steps are strictly followed and I have named the project, package and classes as it is given.
Why is the content not getting copied?
Upvotes: 0
Views: 9238
Reputation: 109567
Both in reading and writing there is missing:
} finally {
writer.close();
}
As:
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file;
String line = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
try {
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
} finally {
reader.close();
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} catch (IOException e) {
throw new RuntimeException("IO Error occured");
}
return returnValue;
}
public void writeTextFile(String fileName, String s) {
FileWriter output;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 2
Reputation: 4324
You FileWriter
object overrides the data written to your file.
Try using this constructor, which appends the data:
FileWriter
public FileWriter(String fileName,
boolean append)
throws IOException
Upvotes: 0