Dan
Dan

Reputation: 639

Writing a list to a file

I'm trying to store all elements in a List in a file for later retrieval so when the program closes that data isn't lost. Is this possible? I've written some code to try, but it's not what I want. This is what I have written so far though.

import java.util.*;
import java.io.*;
public class Launch {
    public static void main(String[] args) throws IOException {
        int[] anArray = {5, 16, 13, 1, 72};
        List<Integer> aList = new ArrayList();
        for (int i = 0; i < anArray.length; i++) {
            aList.add(anArray[i]);
        }
        File file = new File("./Storage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < aList.size(); i++) {
            bw.write(aList.get(i));
        }
        bw.flush();
        bw.close();
    }
}

Suggestions?

Edit: I'm looking for the array itself to be written in the file, but this is what is writing. enter image description here

Upvotes: 3

Views: 8290

Answers (3)

Arun Krishna
Arun Krishna

Reputation: 59

Just learnt a clean solution for this. Using FileUtils of apache commons-io.

File file = new File("./Storage.txt");
FileUtils.writeLines(file, aList, false);

change false to true, if you want to append to file, in case it exists already.

Upvotes: 1

Isaac
Isaac

Reputation: 16736

If you want it to write the actual number, use a PrintWriter instead.

PrintWriter pw = new PrintWriter(new File(...));
pw.print(aList.get(i));

Upvotes: 0

nair.ashvin
nair.ashvin

Reputation: 801

import java.util.*;
import java.io.*;
public class Launch {
    public static void main(String[] args) throws IOException {
        int[] anArray = {5, 16, 13, 1, 72};
        List<Integer> aList = new ArrayList();
        for (int i = 0; i < anArray.length; i++) {
            aList.add(anArray[i]);
        }
        File file = new File("./Storage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < aList.size(); i++) {
            bw.write(aList.get(i).toString());
        }
        bw.flush();
        bw.close();
    }
}

I edited the bw.write line to change the int to a string before writing it.

Upvotes: 4

Related Questions