2014-09-27 3 views
0

임의의 int를 생성하고 파일에 쓰려고합니다. 문제는 필자가 만든 파일을 열 때 내가 int를 찾지 못하고 사각형과 같은 심볼 집합입니다 ... 인코딩 문제입니까? 생성 된 파일에서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

들은 "기호는"당신의 int입니다. 바이너리 파일을 텍스트 편집기에서 열면 바이너리 파일이 보입니다. 파일의 크기는 정확히 4000 바이트이며, 각각 4 바이트로 1000 int를 썼음을 알 수 있습니다. 당신이의 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. 

에는 인코딩 문제가 없습니다. 텍스트 편집기를 사용하여 이진 파일을 열 때 표시되는 내용입니다. 16 진수 편집기로 열어보십시오.

0

텍스트가 아닌 바이너리를 씁니다. 기대치가 잘못되었습니다. 텍스트를 원하면 Writer를 사용하십시오.