简体   繁体   中英

Write String with array as bytes to a file using DataOutputStream

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM