Question

I want all data of Latitude and Longitude which input by user being wrote into WriteGPSData.txt. But this code only write the last input of Latitude and Longitude. Help me solved this.

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;

public class GPS_main {

    public static void main(String[] args) {
        String strFilePath = "WriteGPSData.txt";
        try {
            System.out.println("+++=====GPS POINTS=======+++");
            // GPS p1 = new GPS ();
            GPS[] p2;
            p2 = new GPS[3];
            p2[0] = new GPS();
            // GPS p2 = new GPS();
            for (int i = 0; i < p2.length; i++) {
                p2[i] = new GPS();
                String aa = JOptionPane.showInputDialog("Enter latitude: ");
                double a = Double.parseDouble(aa);
                p2[i].setLat(a);
                String bb = JOptionPane.showInputDialog("Enter longitude: ");
                double b = Double.parseDouble(bb);
                p2[i].setLon(b);
                // System.out.println(p2[i].toGPSString());
                FileOutputStream fos = new FileOutputStream(strFilePath);
                DataOutputStream dos = new DataOutputStream(fos);
                String a2 = Double.toString(a);
                String b2 = Double.toString(b);
                // System.out.println("hello"+a2+b2);
                dos.writeBytes(a2 + "  " + b2);
                dos.close();
            }
        } catch (IOException e) {
            System.out.println("IOException : " + e);
            // System.out.println("   ");
        }
    }
}

Run in BlueJ

Was it helpful?

Solution

Keep these lines outside for loop in the beginning :

 FileOutputStream fos = new FileOutputStream(strFilePath);     
  DataOutputStream dos = new DataOutputStream(fos);

And close the OutputStream once write is complete. You can use finally() and write dos.close(); in it.

In your code, for each iteration a new file is created and hence, old data is overwritten.

OTHER TIPS

The lines

FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);

should appear before entering the for loop. Otherwise the contents of the output file itself be truncated in every iteration. Also you will need to defer closing the DataOutputStream until after the loop has completed

dos.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top