繁体   English   中英

使用DataOutputStream将int写入文件

[英]Write int to file using DataOutputStream

我正在生成随机整数,并尝试将其写入文件。 问题是,当我打开创建的文件时,找不到整数,而是找到一组符号,例如正方形等。这是编码问题吗?

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

}

从创建的文件中粘贴部分副本:

/   O   a   C   ?       6   N       

文档

 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.

没有编码问题。 这就是使用文本编辑器打开二进制文件时看到的。 尝试使用十六进制编辑器打开。

这些“符号”就是您的观点。 如果在文本编辑器中打开二进制文件,则二进制文件看起来就是这样。 请注意,该文件的大小恰好为4000字节,并且您写入了1000个int,每个4个字节。

如果使用DataInputStream读取文件,则将获得原始值:

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

它写二进制而不是文本。 您的期望放错了地方。 如果需要文本,请使用Writer。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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