2014-12-17 4 views
0

두 가지 방법, 둘 다 FileInputStream 객체를 사용합니다. 첫 번째 값은 예상 값을 반환합니다. 이 방법은 잘 작동합니다. 그러나 두 번째 방법은 아무 것도 반환하지 않습니다. 두 번째 메소드에 전달 된 값이 null이 아닙니다. 메서드에 전달 된 파일의 16 진수 형식을 가져와야합니다. 왜 그렇습니까? 친절하게 설명하십시오. 여기 b 이후FileInputStream이 null을 반환합니다.

public String binaryFile1(File file1){ 
     try{ 
     stringBuilder1=new StringBuilder(); 
     is1=new FileInputStream(file1); 
     while(b!=-1){ 
      counter++; 
      b=is1.read(); 
      String s = Integer.toHexString(b).toUpperCase(); 
     if (s.length() == 1) { 
      stringBuilder1.append('0'); 
     } 
      if(counter%5==0){ 
       stringBuilder1.append(s).append("\n"); 
       counter=0; 
      }else 
       stringBuilder1.append(s).append(' '); 

     } 
     is1.close(); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

     return stringBuilder1.toString(); 
} 


public String binaryFile2(File file2){ 
     try{ 
     stringBuilder2=new StringBuilder(); 
     is2=new FileInputStream(file2); 
     while(b!=-1){ 
      counter++; 
      b=is2.read(); //Here b does not get any content assigned. 
      String s = Integer.toHexString(b).toUpperCase(); 
     if (s.length() == 1) { 
      stringBuilder2.append('0'); 
     } 
      if(counter%5==0){ 
       stringBuilder2.append(s).append("\n"); 
       counter=0; 
      }else 
       stringBuilder2.append(s).append(' '); 
     } 
     is2.close(); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

     return stringBuilder2.toString(); //Here stringBuilder2 is null 
} 
+1

과 같이 binaryFile2을 쓸 수 있습니다. 정확하게 목적은 무엇입니까? –

+0

null을 돌려 줄 수있는'FileInputStream' 메서드는 존재하지 않습니다. 여기서 유일한 문제는 잘못된 try/catch 구조입니다. – EJP

+0

try-catch 구조가 제대로 작동하고 있습니다. Elliot Frisch가 문제를 올바르게 잡았습니다. –

답변

3

공유하고 당신이 아직 binaryFile1 후 -1 binaryFile2의 시작을 재설정하지 않는 내 코드입니다. 나는

int b; 
while ((b = is2.read()) != -1) { 
    // ... 
} 

편집, 당신이 사용하는 것이 좋습니다

당신이 완료되면 리소스를 종료하는 것이 중요하다. 또한 가능한 한 가변 범위를 제한하고 시도하는 것이 좋습니다. try-with-resources을 사용하면

public String binaryFile2(File file) { 
    StringBuilder sb = new StringBuilder(); 
    int counter = 0; 
    try (InputStream is = new FileInputStream(file)) { 
     int b; 
     while ((b = is.read()) != -1) { 
      counter++; 
      String s = Integer.toHexString(b).toUpperCase(); 
      if (s.length() == 1) { 
       sb.append('0'); 
      } 
      sb.append(s); 
      if (counter % 5 == 0) { 
       sb.append(System.lineSeparator()); 
       counter = 0; 
      } else { 
       sb.append(' '); 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return sb.toString(); 
} 
+0

그가 binaryFile2 (filename2)를 먼저 호출하고 그 뒤에 binaryFile1 (filename2)을 호출하면 동일한 오류가 다시 발생하지 않습니다. 두 가지 방법 모두에서 "int b"를 초기화해야한다고 생각합니다. 어떻게 생각하니? –

+0

리시 프라 카시 (Rishi Prakash)는 귀하의 제안도 대단히 유효합니다. –

관련 문제