简体   繁体   中英

Write int to file using DataOutputStream

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       

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM