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");
}
}
move your file
and *Writer
creation code to before the loop, otherwise you are creating new Writer
s each iteration. Only the last created Writer
is being closed and flushed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.