Write int to file using DataOutputStream

寵の児 提交于 2020-01-06 19:55:10

问题


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       

回答1:


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.




回答2:


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);
}



回答3:


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



来源:https://stackoverflow.com/questions/26072482/write-int-to-file-using-dataoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!