使用DataOutputStream将int写入文件 [英] Write int to file using DataOutputStream

查看:376
本文介绍了使用DataOutputStream将int写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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       


推荐答案

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.

这篇关于使用DataOutputStream将int写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆