-3

I'm writting some code that needs to store some data like this:

double[] VERTS = {
            0.000000, -7.350000, 21.750000,
            0.000000, -9.145293, 21.750000
}

However, I want the double[] VERTS array to be in an external file. Is this possible?

EDIT: And how can I read it back?

Thanks in advance.

  • 2
    arrays are stored in memory . to put them in a file you need `Serialization` – Ramanlfc Feb 29 '16 at 18:01
  • 1
    Yes, it is possible. There are many ways to do so. – Raedwald Feb 29 '16 at 18:03
  • Ask google. You will have everything. :) – Md. Shohan Hossain Feb 29 '16 at 18:06
  • Take a look at [this example](http://www.jguru.com/faq/view.jsp?EID=34789) in order to learn how to do it. Also, mind what @Ramanlfc has said - the [concept](http://stackoverflow.com/questions/447898/what-is-object-serialization) of [Serialization](https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html). – António Ribeiro Feb 29 '16 at 18:06

3 Answers3

5

This is what DataOutputStream # writeDouble does.

new DataOutputStream(new FileOutputStream("file.txt")).writeDouble(1.02d);

A Java >= 7 buffered solution which will take care of closing resources using a try-with-resources block :

try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("file.txt")))) {
    for (double vert : VERTS) {
        os.writeDouble(vert);
    }
} catch (IOException e) {
    e.printStackTrace();
}
Bax
  • 4,260
  • 5
  • 43
  • 65
0

The concept you are talking about is called serialization in Java.

Use ObjectOutputStream to write an object into a file:

try {
    FileOutputStream fos = new FileOutputStream("output");
    ObjectOutputStream oos = new ObjectOutputStream(fos);   
    oos.writeObject(obj); // write array obj to ObjectOutputStream
    oos.close(); 
} catch(Exception ex) {
    ex.printStackTrace();
}
FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
0

You can use ObjectOutputStream

FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);

double[] VERTS = {
                0.000000, -7.350000, 21.750000,
                0.000000, -9.145293, 21.750000
        };

        oos.writeObject(VERTS);
        oos.close();
giannisf
  • 2,479
  • 1
  • 17
  • 29