Murray Ross
Murray Ross

Reputation: 21

Output to file from arraylist not working - java

I'm trying to create a program that outputs a bunch of integers from an arraylist to a file, however all I get is a bunch of question marks in the .dat file. Can anyone see what my problem is?

   BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new FileWriter("energy.dat"));
                for(int x = 0; x< energy.size(); x++){
                writer.write(energy.get(x));
                }
            } catch (IOException e) {
                System.err.println(e);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        System.err.println(e);
                    }
                }
            }

Upvotes: 0

Views: 60

Answers (1)

rzymek
rzymek

Reputation: 9281

Assuming energy is List<Integer> you're calling BufferedWriter.write(int). This method is not writing a text representation of the number. To write 1 you'd have to call write like this: writer.write((int)'1'). This is not the same as writer.write(1).

Replace

writer.write(energy.get(x));

with

String s = String.valueOf(energy.get(x));
writer.write(s, 0, s.length();

Upvotes: 1

Related Questions