3

java에 이상한 문제가 있습니다. ObjectOutputStream에 byte []를 쓰고 싶으면 거기에 새로운 파일을 씁니다. 해당 바이트 배열은 디스크에서 읽은 다른 파일을 나타냅니다.ObjectOutputStream에 쓰여진 것보다 ObjectInputStream에서 다른 byte [] 읽음

나중에 새로 만든 파일에 쓰고 난 후, 그 파일에서 읽고 싶습니다. 다만, ObjectInputStream로부터 읽힌 byte []는 기입해진 바이트와는 다릅니다.

그리고 그것은 내 질문입니다. 왜 도대체 [byte]가 다른가요? 나는 당신이 날 도울 수 있기를 바랍니다

import java.io.*; 
import java.net.URL; 
import java.nio.channels.Channels; 
import java.nio.channels.ReadableByteChannel; 
import java.security.MessageDigest; 
import org.bouncycastle.util.encoders.Hex; 

public class MyTest { 

    public static void main(String[] args) throws Exception { 

     // 1st step: 
     // ------------------------------------------------ 
     byte[] data = openFile(); 

     // Create file to write 
     FileOutputStream fos = new FileOutputStream(new File("test")); 
     ObjectOutputStream oosf = new ObjectOutputStream(fos); 
     // Write byte[]-length and byte[] 
     oosf.writeInt(data.length); 
     oosf.write(data); 

     // Flush & Close 
     fos.flush(); 
     fos.close(); 

     // Print hash value of saved byte[] 
     try { 
      final MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); 
      messageDigest.reset(); 
      System.out.println(new String(Hex.encode(messageDigest.digest(data)))); 
     } catch (Exception e) { 
     } 

     // 2nd step 
     // ------------------------------------------------ 

     // Open just saved file 
     FileInputStream fis = new FileInputStream(new File("test")); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     // Read the length and create a byte[] 
     int length = ois.readInt(); 
     byte[] dataRead = new byte[length]; 
     // Read the byte[] itself 
     ois.read(dataRead); 

     // Print hash value of read byte[] 
     try { 
      final MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); 
      messageDigest.reset(); 
      System.out.println(new String(Hex.encode(messageDigest.digest(dataRead)))); 
     } catch (Exception e) { 
     } 

     // Both printed hash values should be the same 

    } 

    private static byte[] openFile() throws Exception { 
     // Download a sample file which will be converted to a byte[] 
     URL website = new URL("http://www.marcel-carle.de/assets/Cryptonify/Cryptonify-1.7.8.zip"); 
     ReadableByteChannel rbc = Channels.newChannel(website.openStream()); 
     FileOutputStream fos2 = new FileOutputStream("tmp"); 
     fos2.getChannel().transferFrom(rbc, 0, 1 << 24); 
     fos2.flush(); 
     fos2.close(); 

     // Open downloaded file and convert to byte[] 
     File selectedFile = new File("tmp"); 
     FileInputStream fis1 = new FileInputStream(selectedFile); 
     byte[] data = new byte[(int) selectedFile.length()]; 
     fis1.read(data); 
     fis1.close(); 


     return data; 
    } 
} 

:

가 명확하고 모두 확인 할 수 있도록하기 위해, 나는 정확히 무슨 뜻인지 보여줄 것이다 짧은 프로그램을 썼다!

+0

어떻게 다른가요? – zmbq

+0

그들은 하나의 인덱스에서 거의 모든 바이트가 서로 다릅니다 ... 더 이상 확인하지 않고 해시 값을 생성하고 서로 다릅니다. – Ph3n1x

+2

FileOutputStream이 아닌 가장 바깥 쪽 스트림 (즉 ObjectOutputStream)을 플러시하고 닫으십시오. 그런 다음 예외 무시를 중지하십시오. 그런 다음 InputStream.read()의 반환 값을 무시한 다음 메서드가 -1을 반환 할 때까지 루프를 읽습니다. 즉, 객체를 쓰거나 읽지 않는 경우 객체 스트림을 사용해야하는 이유는 무엇입니까? –

답변

5

예외를 무시하고 있습니다. 당신은 올바른 흐름을 닫지 않습니다; read()이 버퍼를 채우고 있다고 가정하고 있습니다. readFully()을 사용하십시오. 당신은 객체를 쓰지 않으므로 DataInputStreamDataOutputStream을 사용하고 약간의 공간을 절약하십시오.

+0

이 코드 단편은 간단한 서면 예제이지만 오류가 발견되어 잘못된 스트림을 닫았습니다. 내 실제 프로그램에서는 readFully()를 사용하여 샘플 프로젝트에 복사하는 것을 잊어 버렸다. – Ph3n1x

+0

감사합니다. 유사한 문제를 파악할 수 없었습니다. read()를 readFully()로 바꿨습니다. 이제는 모두 잘되었습니다 !! –

관련 문제