Joy Kid
Joy Kid

Reputation: 1

Copy text from one file to another using Java

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

Answers (3)

Naresh M
Naresh M

Reputation: 29

Close your writers and readers after the operation, it works.

Upvotes: 1

Joop Eggen
Joop Eggen

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

Mechkov
Mechkov

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

Related Questions