0

I need your help with the below code , I am not able to append the text (Hi in my example). the file is being created and I am having inside of it only 1 Hi, however I am looping inside of it ( when I run the cmd I can see it is looping and system printing several hi ) but why i am having in the file 1 hi ?

I made sure that this is true fw = new FileWriter(file.getAbsoluteFile(), true);

            try
            {

                LineNumberReader rdr = new LineNumberReader(new FileReader(directory+"/Ant_log.log"));


                String timeStamp = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Calendar.getInstance().getTime());
                BufferedWriter bw = null;
                FileWriter fw = null;
                File file = new File(directory+"/Log-Missing-scripts.txt");

                String line1 ="";
                    while((line1 = rdr.readLine())!= null)               
                    {

                        // if file doesnt exists, then create it
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        // true = append file
                        fw = new FileWriter(file.getAbsoluteFile(), true);
                        bw = new BufferedWriter(fw);
                        System.out.println(rdr.getLineNumber());
                         if (rdr.getLineNumber()== 3) 
                            {
                                System.out.println("Hi");

                        bw.write("Hi");
                        break;
                            }
                    }
                    bw.close();
                    writer.close();


            }
            catch(Exception e)
            {
                System.out.println("ERROR : In Log File");

            }
        }
1
  • @ScaryWombat thanks it work please added as an answer to close this question Commented Mar 17, 2017 at 7:24

1 Answer 1

1

move your file and *Writer creation code to before the loop, otherwise you are creating new Writers each iteration. Only the last created Writer is being closed and flushed

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.