2014-09-27 33 views
0

我正在生成随机整数并试图将它们写入文件。问题是,当我打开我创建的文件时,我没有找到我的整数,但是有一组符号像正方形等等。它是编码问题吗?使用DataOutputStream将int写入文件

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  

回答

0

这些 “符号” 是你的整数。这就是二进制文件在文本编辑器中打开时的样子。请注意,该文件的大小正好为4000字节,并且您写入了1000个整数,每个长度为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); 
} 
2

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. 

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

0

它写入二进制文件,而不是文本。你的期望是错位的。如果你想要文字,请使用Writer。