0

I have this code that gets GPS data from input stream make the test file but there is nothing inside. Can you please tell me what is the problem in here?

public void run ()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ( ( len = this.in.read(buffer)) > -1 )
                {
                    String gpsInfo = new String(buffer,0,len);
                    PrintWriter data = new PrintWriter("test.txt");
                    data.println(gpsInfo);
                    System.out.print(gpsInfo);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }

I am getting the right console output.

enter image description here

Mix Austria
  • 925
  • 2
  • 15
  • 35

2 Answers2

2

You are opening the same file repeatedly in the while loop. You should open before going into the loop. Also flush() and close() the stream.

      PrintWriter data = new PrintWriter("test.txt");
      while((len = this.in.read(buffer)) > -1) {
        String gpsInfo = new String(buffer,0,len);
        data.println(gpsInfo);
        System.out.print(gpsInfo);
      }
      data.flush();
      data.close();

If you are using java 7 and above then you can open the file in try block itself. It will be closed automatically once your code in the try block completes. But don't forget to flush() the data.

  public void run () {
    byte[] buffer = new byte[1024];
    int len = -1;
    try (PrintWriter data = new PrintWriter("test.txt")) {
      while((len = this.in.read(buffer)) > -1) {
        String gpsInfo = new String(buffer,0,len);
        data.println(gpsInfo);
        System.out.print(gpsInfo);
      }
      data.flush();
    }
    catch ( IOException e ) {
      e.printStackTrace();
    }
  }
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
  • @MixAustria It is writing the output into file. I would suggest you to provide the absolute path of the file, for testing purpose. – YoungHobbit Oct 06 '15 at 03:55
0

The way you doing is actually correct. Once the data is written into a text file, close the PrintWriter instance.

data.close();

If you want to know about more information check this link

Code Snippet:

PrintWriter data = new PrintWriter("test.txt");
String gpsInfo = null;

while ( ( len = this.in.read(buffer)) > -1 )
{
     gpsInfo = new String(buffer,0,len);
     data.println(gpsInfo);
     System.out.print(gpsInfo);
}

data.close();
Community
  • 1
  • 1
Vignesh Shiv
  • 1,129
  • 7
  • 22