0

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

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
nani
  • 389
  • 9
  • 32
  • 1
    You open and close the output file each time through the input loop, when you reopen it, you're wiping out what was written the last time. – Ray Stojonic Apr 23 '13 at 12:59

2 Answers2

4

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.

Divya Motiwala
  • 1,659
  • 1
  • 16
  • 24
3

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();
Reimeus
  • 158,255
  • 15
  • 216
  • 276