TwoThumbSticks TwoThumbSticks - 3 months ago 39
Java Question

Buffered Writer not writing inside do while loop

I am trying to read a source file (src.txt) and write its content to new files for every 10 lines.

I am encountering issues with my buffer reader inside the do while loop.
BufferReader works fine when I debug the values are correct. BufferedWriter writes new files correctly but does not write the BufferReader strings inside the files generated. What am I doing wrong?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Home
{
public static void main(String[] args)
{
BufferedReader br = null;
//BufferedWriter bw = null;


try{
int fileNumber = 1;
br = new BufferedReader(new FileReader("src.txt"));

final String header = br.readLine();
String line= "";

do{
BufferedWriter bw = new BufferedWriter(new FileWriter("output" +fileNumber+ ".txt"));

for( int i = 0; i <= 10 && line != null; i++)
{
if(i == 0){
writeHeader(bw, header);

}else{
//System.out.println(br.readLine());
bw.write(br.readLine());
bw.write(System.getProperty("line.separator"));
}
}
fileNumber++;
}while(br!=null);

}
catch(Exception e){

}finally{
//br.close();
//bw.close();
}
}

public static void writeHeader(BufferedWriter bw, String header){
try {
System.out.println("HEADER VALUE = " + header);
bw.write(header);
bw.write(System.getProperty("line.separator"));

} catch (IOException e) {

e.printStackTrace();
}

}

Answer

You are never closing your BufferedWiter, so try

fileNumber++;
bw.close ();

but also testing for br != null is never going to work

consider changing your program to something like

while ((line = br.readLine ()) != null) {

   if (lineNum++ == 10) {
       closeandReopen ();
   }

   bw.write (line);
   bw.newLine ();

}