Danson
Danson

Reputation: 425

BufferedWriter overwriting itself

I want to read in a file and create a duplicate of the file but my code only write the last line in the file. How do I make so that whenever I call write(), it writes to a new line. I want to create a new file for the duplicate so I can't add true to FileWriter constructor.

This is my code:

    //Create file reader
    BufferedReader iReader = new BufferedReader(new FileReader(args[1]));

    //Create file writer
    BufferedWriter oWriter = new BufferedWriter(new FileWriter(args[2], true));

    String strLine;
    //reading file
    int iterate = 0;
    while((strLine = iReader.readLine()) != null)  {
        instructions[iterate] = strLine;
    }

    //creating duplicate
    for(int i = 0; i < instructions.length; i++) {
        if(instructions[i] != null) {
            oWriter.write(instructions[i]);
            oWriter.newLine();
        }  else {
            break;
        }
    }

    try {
        iReader.close();
        oWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Upvotes: 0

Views: 112

Answers (2)

dkatzel
dkatzel

Reputation: 31648

You are not incrementing iterate

 int iterate = 0;
 while((strLine = iReader.readLine()) != null)
{
    instructions[iterate] = strLine;
    iterate++;
}

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160181

You're not updating the index of the instructions array.

In addition, it's not immediately clear why you're copying the file this way anyway; why bother doing it line-by-line? Or just use a utility class, like from Apache Commons.

Upvotes: 0

Related Questions