-1

I'm trying to read the file "ab.txt" and saving its content in "Output.txt" Kth times,so i'm suppose to get the content of input file K times in output file,but i'm getting only once whereas it is printing on console Kth times.

 import java.io.*;
    import java.util.Scanner;

    class PrintStreamTest1
    {
       public static void main(String... l)throws IOException
       {
         int k=0;
         long avgTime=0;

        while(k<100)
        {
          long startTime=System.nanoTime();
          String s;
          Scanner fin=new Scanner(new BufferedInputStream(new FileInputStream("ab.txt")));
          PrintStream output=new PrintStream("Output.txt");
          while(fin.hasNextLine())
          {
             s=fin.nextLine();
             System.out.println(s);
             output.print(s+"\n");
          }

          avgTime=avgTime+((System.nanoTime()-startTime)/10000000);
          fin.close();
          output.close();
          k++;
        }

        System.out.println("\n "+ avgTime+"ms");
       }    

    }
Shadab Faiz
  • 2,380
  • 1
  • 18
  • 28

1 Answers1

1

You are using the wrong constructor as you can see in the Javadoc :

PrintStream(String fileName)
...
fileName The name of the file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

You should open the file associated with the PrintStream in append mode if you don't want the content of that file overwritten in each iteration of your loop :

PrintStream output = new PrintStream(new FileOutputStream("Output.txt",true));

Alternately, just open the file once before the loop and close it once after the loop.

Eran
  • 387,369
  • 54
  • 702
  • 768