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.
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();
}
}