2011-03-17 3 views
0

Java를 사용하여 먼저 문자열 시퀀스를 작성한 다음 바이트 시퀀스를 파일에 기록하려고합니다. 바이트 배열 때문에 FileOutputStream을 사용하기 시작했습니다. API를 검색 한 후 FileOutputStreamString을 쓸 수없고 intbyte s이므로 DataOutputStream으로 전환 함을 깨달았습니다. 프로그램을 실행하면 예외가 발생합니다. 왜?어떻게 문자열의 시퀀스를 작성한 다음 파일에 바이트 배열을 쓸 수 있습니까?

여기 내 코드의 일부입니다 :

라인
try { 
      // Create the file 
      FileOutputStream fos; 
      DataOutputStream dos; // = new DataOutputStream("compressedfile.ecs_h"); 
      File file= new File("C:\\MyFile.txt"); 
      fos = new FileOutputStream(file); 
      dos=new DataOutputStream(fos); 

      /* saves the characters as a dictionary into the file before the binary seq*/ 
      for (int i = 0; i < al.size(); i++) { 
       String name= al.get(i).name; //gets the string from a global arraylist, don't pay attention to this! 
       dos.writeChars(name); //saving the name in the file 
      } 

      System.out.println("\nIS SUCCESFULLY WRITTEN INTO FILE! "); 

      dos.writeChars("><"); 
      String strseq; 

      /*write all elements from the arraylist into a string variable*/ 
      strseq= seq.toString(); 
      System.out.println("sTringSeq: " + strseq); 

      /*transpose the sequence string into a byte array*/ 
      byte[] data = new byte[strseq.length()/8]; 

      for (int i = 0; i < data.length; i++) { 
       data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2); 
       dos.write(data[i]); 
      } 


      dos.flush(); 
      //Close the output stream 
      dos.close(); 
} catch(Exception e){} 
+9

예외가 포함 된 질문을 작성할 때마다 예외가 무엇인지 * 알려주십시오. –

+0

미안하지만 나는 모른다. 나는 try catch를 사용하고있다! – elena

+0

문제는 빈 캐치 블록을 사용하고 있다는 것입니다. 나쁜 생각입니다. 예외가 무엇인지 알기 위해 스택 추적을 인쇄해야합니다. – javanna

답변

0

코드의 문제점은 마지막 for 루프가 잘못된 바이트 수를 세고 있다는 것입니다. 아래 코드는 테스트 데이터를 파일에 쓰는 문제를 해결합니다. 이것은 내 컴퓨터에서 작동합니다.

public static void main(String[] args) { 

    ArrayList<String> al = new ArrayList<String>(); 
    al.add("String1"); 
    al.add("String2"); 

    try { 
     // Create the file 
     FileOutputStream fos = new FileOutputStream("MyFile.txt"); 
     DataOutputStream dos = new DataOutputStream(fos); 

     /* saves the characters as a dictionary into the file before the binary seq */ 
     for (String str : al) { 
      dos.writeChars(str); 
     } 

     System.out.println("\nIS SUCCESFULLY WRITTEN INTO FILE! "); 

     dos.writeChars("><"); 
     String strseq = "001100111100101000101010111010100100111000000000"; 

     // Ensure that you have a string of the correct size 
     if (strseq.length() % 8 != 0) { 
      throw new IllegalStateException(
        "Input String is cannot be converted to bytes - wrong size: " 
          + strseq.length()); 
     } 

     int numBytes = strseq.length()/8; 
     for (int i = 0; i < numBytes; i++) { 
      int start = i * 8; 
      int end = (i + 1) * 8; 
      byte output = (byte) Integer.parseInt(strseq.substring(start, end), 2); 
      dos.write(output); 
     } 

     dos.writeChars("> Enf of File"); 
     dos.flush(); 
     // Close the output stream 
     dos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

(나는 그것이 텍스트가 테스트 파일 이름이 .txt로 끝나는에서 파일의 가정) 몇 가지 문제가 않는 테스트 파일에 직접 바이트를 작성하는 방법은, 가장 눈에 띄는 하나가되는 그 텍스트 편집자는 널 문자를 아주 잘 처리/표시하지 않습니다 (마지막 테스트 바이트는 00000000 또는 null 임). 바이트를 읽을 수있는 바이트로보고 싶다면 Base64 인코딩을 사용하여 인코딩을 조사 할 수 있습니다.

+0

감사합니다. 작동 중입니다. – elena

+0

이 특정 파일을 읽을 때 문자열로 인식하지 못하고 첫 번째 부분을 의미합니다. 뭐라 구요? – elena

0

:

data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2); 

매우 의심스럽게 보이는 ...

당신이 strseq 그 값에 대한 이동 정보를 제공 할 수 있습니까?

+0

예를 들어 스트레스는 다음과 같습니다. String strseq = "001100111100101000101010111010100100111000000000"; – elena

+0

문자열에 0과 1 만 있습니까? – Stephan

+0

예 0과 1 – elena

0

이 코드는 어떻게됩니까?

이 코드 :


     byte[] data = new byte[strseq.length()/8]; 

     for (int i = 0; i < data.length; i++) { 
      data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2); 
      dos.write(data[i]); 
     } 

FileWriter 클래스와


     byte[] data = strseq.getBytes(); 
+0

strseq는 예를 들어 "001100111100101000101010111010100100111000000000"을 보유하는 문자열입니다. – elena

+0

그래서 strseq의 길이가 8 자보다 큰지 확인하는 것을 잊지 마십시오. – Stephan

0

이되고 당신은 파일 쓰기 작업의 좋은 추상화가있다.

이 클래스는

당신은이 클래스가 다른 OutputStreams을 대체 할 수 있습니다 ... 당신이 당신의 파일을 작성하는 데 도움이 될 수 있습니다. 그것은 당신이 문자열과 바이트 배열을 파일에 쓰기를 원하는 모든 방법을 가지고 있습니다.

관련 문제