Lok Lok - 5 months ago 7
Java Question

How to write ArrayList<Double> into a file in Java

I want to write the

ArrayList<Double>
array into the file in such a way that when I double click on the file then the file opens and the user can read the data.

I have tried the
DataOutputStream
&
RandomAccessFile
; both works fine but when I double click on the file it shows data which is not in readable form.

I tried this:

ArrayList<Double> larr=new ArrayList<Double>();
larr.add(5.66);
larr.add(7.89);
try{
FileOutputStream fos = new FileOutputStream("out.txt");
DataOutputStream dos = new DataOutputStream(fos);
for(Double d:larr)
dos.writeDouble(d);
dos.close();
} catch(Exception ex) {
ex.printStackTrace();
}


But now the case is that when I open the file
out.txt
by double clicking on it. It comes in non-readable form.

Answer

I would use a PrintWriter to get human readable values to out.txt (and I would specify the parent folder, personally; I like the user's home directory). Also, I would prefer a try-with-resources close and a method. Something like,

public static void writeList(List<Double> al) {
    File f = new File(System.getProperty("user.home"), "out.txt");
    try (PrintWriter pw = new PrintWriter(f)) {
        for (Double d : al) {
            pw.println(d);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Also, you could declare and initialize larr1 in one line like

List<Double> larr = new ArrayList<>(Arrays.asList(5.66, 7.89));

1And please program to the List interface.

Comments