Write int to file using DataOutputStream

2019-09-14 08:18发布

I'm generating random ints and trying to write them down to a file. The problem is when I open the file I've created I don't find my ints but a set of symbols like squares etc... Is it a problem of encoding ?

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GenerateBigList {

    public static void main(String[] args) {
        //generate in memory big list of numbers in  [0, 100]
        List list = new ArrayList<Integer>(1000);
        for (int i = 0; i < 1000; i++) {
            Double randDouble = Math.random() * 100;
            int randInt = randDouble.intValue();
            list.add(randInt);
        }

        //write it down to disk
        File file = new File("tmpFileSort.txt");
        try {

            FileOutputStream fos = new FileOutputStream("C:/tmp/tmpFileSort.txt");
            DataOutputStream dos = new DataOutputStream(fos);
            writeListInteger(list, dos);
            dos.close();    

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeListInteger(List<Integer> list, DataOutputStream dos) throws IOException {
        for (Integer elt : list) {
            dos.writeInt(elt);
        }
    }

}

A partial copy paste from the created file:

/   O   a   C   ?       6   N       

3条回答
三岁会撩人
2楼-- · 2019-09-14 08:35

From the doc:

 public final void writeInt(int v) throws IOException
    Writes an int to the underlying output stream as four bytes, high byte first. If no exception is thrown, the counter written is incremented by 4.

There is no encoding problem. That is what you see when you open a binary file with a text editor. Try to open with a hex editor.

查看更多
Deceive 欺骗
3楼-- · 2019-09-14 08:38

It writes binary, not text. Your expectations are misplaced. If you want text, use a Writer.

查看更多
Emotional °昔
4楼-- · 2019-09-14 08:54

Those "symbols" are your ints. That's what binary files look like if you open them in a text editor. Notice that the file is exactly 4000 bytes in size, and you wrote 1000 ints, at 4 bytes each.

If you read the file in with a DataInputStream you will get the original values back:

try (DataInputStream dis = new DataInputStream(
    new BufferedInputStream(new FileInputStream("C:/tmp/tmpFileSort.txt")))) {
    for (int i = 0; i < 1000; i++) {
        System.out.println(dis.readInt());
    }
} catch (IOException e) {
    throw new RuntimeException(e);
}
查看更多
登录 后发表回答