How to add a line to a file or until a newline appears?

Input file:

Online_system_id
bank_details
payee
credit_limit
loan_amount

Online_system_id
bank_details
payee
credit_limit
loan_amount

Expected Result:

Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id

Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id

Below is the code for reference.
I want to add a line after each entry before meeting an empty line.
What changes do I need to make?

String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
    if(!line.contains("proc_online_system_id")){
        flag=1;                 
    }

}
if(flag==1)
    out.print("proc_online_system_id");
+4
source share
3 answers
String line;
PrintStream out = null;
BufferedReader br = null;
try {
  out = new PrintStream(new FileOutputStream(outputFile)); 
  br = new BufferedReader(new FileReader(inputFile)); 
  while((line=br.readLine())!=null){
    if(line.trim().isEmpty()) {            
        out.println("proc_online_system_id");   //print what you want here, BEFORE printing the current line         
    }
    out.println(line);        //always print the current line
  }

} catch (IOException e) {
    System.err.println(e);
} finally { 
  try{
    out.close(); 
    br.close();
  } catch (Exception ex) {
    System.err.println(ex);
  }
}

And do not forget further out.close();and br.close();. This solution only stores the current line in memory, unlike the Dakkaron answer , which is correct, but you must save the entire file in memory (in an instance of StringBuilder) before writing to the file.

EDIT: after Vixen 's comment, here is the link if you have java 7 and you want to use try with resources in your solution.

+1

String line;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
   if (!line.trim().isEmpty()){
      line+="\n";
    }
   //System.out.println(line);       
} 
+1

Buffer each block. So what do you do, read the file line by line and save the contents of the current block in StringBuilder. When you come across an empty string, add extra data. When you have done this with the whole file, write the contents of StringBuilder to the file.

String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
    if(!line.contains("proc_online_system_id")){
         flag=1;                
    }
    if (line.isEmpty() && flag==1) {
        flag=0;
        builder.append("proc_online_system_id\n");
    }
    builder.append(line).append("\n");
}
out.print(builder.toString());
+1
source

All Articles