Java: Unable to Concatenate to file using BufferedWriter and FileWriter

I am trying to use BufferedWriter and FileWriter to concatenate the text contents of a file located in "C:\\Source"
to a file of a same name in the "C:\\Destination" directory. I am reading the contents of the source file into an ArrayList<String> , and trying to write it to attach it to the end of the file in the "C:\\Destination" directory.
I set the append parameter of FileWriter to true.

The problem is that the destination file never gets written.  What am I doing wrong here?

The code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class TestConcatenateFiles {
    
    public static void main(String[] args) {
        
        String relativeSourceFileName = "Test1.txt";
        String sourceDirPath = "C:\\Source";
        String destDirPath = "C:\\Destination";
        
        processResultInSourceDirIfExistsInDestDir(relativeSourceFileName, sourceDirPath, destDirPath);
                                                                                                                  
    }
    
    
    
    // See if file 'relativeSourceFileName' exists with earlier file date in 'destDirPath' location
    // if it does, than read the file from 'destDirPath' and concatenate to this file the same filename 
    // in 'sourceDirPath'
    private static void processResultInSourceDirIfExistsInDestDir(String relativeSourceFileName, String sourceDirPath, String destDirPath){
        
        // See if file exists in the destination folder:
        File fileOnServer = new File(destDirPath + "\\" + relativeSourceFileName);
        String line = "";
        ArrayList<String> linesListResultFile = new  ArrayList<String>();
        
            if(fileOnServer.exists() && !fileOnServer.isDirectory()) {   // If file exists and it is not directory, 
                // then concatenate current test results to the file on server and save it at local
                // folder to be backed up later on server.
                
                try {
                            // FileReader reads text files in the default encoding:
                            FileReader fileReader = new FileReader(sourceDirPath + "\\" + relativeSourceFileName);
                            // wrap FileReader in BufferedReader:
                            BufferedReader bufferedReader = new BufferedReader(fileReader);

                            while((line = bufferedReader.readLine()) != null) {
                                linesListResultFile.add(line);
                            }    
                            // Close file
                            bufferedReader.close();            
                        }
                        catch(FileNotFoundException ex) {
                            System.out.println(
                                "File not found, unable to open file '" + 
                                sourceDirPath + "\\" + relativeSourceFileName + "'");                
                        }
                        catch(IOException ex) {
                            System.out.println(
                                "Error reading file '" 
                                + sourceDirPath + "\\" + relativeSourceFileName + "'");                   
                        }
                    }
    
        System.out.println();
        // Append to end of file on server, in a try-catch:
        
        try{
                // Open file on server, and with append = true setting concatenate to file:
                FileWriter fileWriter = new FileWriter(fileOnServer.getName(),true);
                            BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
            
                            Iterator it = linesListResultFile.iterator();
                            
                                while(it.hasNext()){
                                    bufferWriter.write((String) it.next());
                            } 
                            
                            bufferWriter.flush();
                            bufferWriter.close();
                            System.out.println("Done writing file");
             
                    }catch(IOException e){
                    System.out.println("Error writing file on server");    
                          //  e.printStackTrace();
                    }
    }  // End of processResultInSourceDirIfExistsInDestDir() method
            
}

Open in new window

AttilaBAsked:
Who is Participating?
 
CEHJCommented:
FileWriter fileWriter = new FileWriter(fileOnServer.getName(),true);

Open in new window

Will strip the path of all but the name, meaning that you will write instead to a file in the current directory of the same name
You want
FileWriter fileWriter = new FileWriter(fileOnServer,true);

Open in new window

And you should use a PrintWriter probably
0
 
CEHJCommented:
Nothing obvious to me. You should put in some debugging sysouts (it should properly have logging)
0
 
AttilaBAuthor Commented:
Well, What do mean 'some debugging sysouts?  I single step through it in debug mode. No errors.
No exceptions. It just doesn't write the file. I don't know what code I would put in to catch that.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
CEHJCommented:
System.out.println(fileOnServer.exists() && fileOnServer.isFile() && fileOnServer.canWrite());

Open in new window


for example
0
 
AttilaBAuthor Commented:
Well, it is running fine, it just doesn't write to the file.
See screenshot:

Screen shot of running with output file not updated
I tried some newer code that uses newer classes for the same functionality, starting from Java 7 or later, and that is flaky too (works some of the time).

I have successfully done concatenating before, by reading the file contents of old file to ArrayList<String>, closing the file, then adding the contents of the new file to the same ArrayList<String> , then opening the old file again and  writing the contents of ArrayList<String> to new file. Sometimes I had to do it in such a way that I write to a temp file and rename it to the old file name to avoid errors.  Really convoluted.

Did actually straightforward  concatenating to text files ever work for anybody, using Java?
0
 
CEHJCommented:
MAKE SURE that the file to which you're appending is NOT opened by ANY other app (such as an editor like Notepad)
0
 
AttilaBAuthor Commented:
It was not. I just opened it afterwards to show you in the screenshot. My code is just a very short single class with a main method in it. Could you perhaps make a couple of folders yourself put in 2 text files with a line or two each,
and see if on your machine they get concatenated into into one of the files if you run the code?
0
 
AttilaBAuthor Commented:
I am using Windows 7 64-bit and a 32-bit Java JDK 1.7. I need to use  32 bit, because the class files need to be compatible with 64 bit and 32 bit Windows. Everything else Java runs fine on this setup.
0
 
AttilaBAuthor Commented:
FilileWriter doesn't work for concatenation.  But, PrintWriter does exactly what I need:

        try{
                        FileWriter fw = new FileWriter(fileOnServer,true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter pw = new PrintWriter(bw);
                        
                        Iterator it = linesListResultFile.iterator();
                        
                        while(it.hasNext()){
                                pw.print((String) it.next());
                                pw.println();
                        } 
                        
                    pw.close();
            
                    System.out.println("Done writing file");
             
                    }catch(IOException e){
                    System.out.println("Error writing file on server");    
                    }

Open in new window


Thanks for your help.
0
 
CEHJCommented:
Or more simply

for (String line : linesListResultFile) {
   pw.println(line);
}

Open in new window

0
 
AttilaBAuthor Commented:
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.