Search code examples
javaarraysfileoperations

Writing file to array it writes only last record in my array


I want to print my console lines to txt file.I want this operation in else statement.But it writes to file only last record.How can i fixed it? When i try buffered reader it cant solve my problem.Thanks everybody.Have a good day.Which solution do you advice to me?

for(int iy=0;iy<arr.length;iy++){

    if( arr[iy].contains("•") || arr[iy].contains("Contact") || arr[iy].contains("@") || arr[iy].contains("Activities and Societies") || arr[iy].contains("Page")){

    }               
    else if(arr[iy].contains("Summary")){
        //System.out.println(arr[iy]+"enes");
        while(exit==false){
            iy++;

            if(arr[iy].contains("Experience")){
                exit=true;
            }
        }           
    }               
    else if(arr[iy].contains("Skills") || arr[iy].contains("Languages")){

        while(exit==false){
            iy++;

            if(arr[iy].contains("Education")){
                exit=true;
            }
        }
    }                               
    else  
    {                   
        System.out.println(arr[iy]); 

        try(PrintWriter bw = new PrintWriter(new FileWriter(FILENAME2))){

            bw.write(arr[iy]);
            //out.newLine();
            bw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }                       
}

Solution

  • Your code is very convoluted, but the reason for just the last line being written is clear - you open the file for each line you are about to output to it, and overwrite the previous contents of the file.

    • You shouldn't open and close the file for each line. Open it once before the loop, and close it after the loop.

    • If it did make sense to open and close the file multiple times, you should have opened the FileWriter in append mode (by using new FileWriter(FILENAME2,true)).