2013-04-24 11 views
2

이 코드를 실행하려고하는데 유효한 인수를 제공하고 있지만 여전히 줄 번호가 잘못 표시됩니다. 34 및 35에서 지역 변수 fin 및 fout이 초기화되지 않았을 수 있습니다. 이 enter code heretry 블록 안에 FileIStream 변수가 초기화되지 않았을 수 있습니다. 오류

package maxbj.myTest.p1; 
import java.io.*; 
public class CopyFile { 
public static void main(String[] args)throws IOException { 

    int i; 
    FileInputStream fin; 
    FileOutputStream fout; 

    try{ 
     //trying to open input file 
     try{ 
      fin=new FileInputStream(args[0]); 
     }catch(FileNotFoundException e){ 
      System.out.println("Input file not found"); 
      return; 
     } 

     //trying to open output file 
     try{ 
      fout=new FileOutputStream(args[1]); 
      return; 
     }catch(FileNotFoundException e){ 
      System.out.println("Output file cannot be opened or created"); 
      return; 
     }  
    }catch(ArrayIndexOutOfBoundsException e){ 
     System.out.println("Array index out of bound exception"); 
    } 

    //code to copy file 
    try{ 
     do{ 
      i=fin.read(); 
      if(i!=-1) fout.write(i); 
     }while(i!=-1); 
    }catch(IOException e){ 
     System.out.println("File Error"); 
    } 
    fin.close(); 
    fout.close(); 
} 
} 

이 코드는 책이다 PS- "JAVA COMPLETE에 refrence"를 해결하는 방법

+0

@SotiriosDelimanolis 해결 방법이 아니며 해결 방법 일뿐입니다. 픽스는 'fin'이 초기화되지 않은 경로가 없음을 확인합니다. 상대적으로 간단한 일입니다. – dasblinkenlight

답변

2

컴파일러는 권리 (그리고 책들은 출판 전에 코드를 컴파일 시도한다, 잘못) 코드가 fin.read() 라인에 도달 할 때까지 fin이 초기화되지 않은 채로 있으면 코드를 통과하는 경로가 있습니다.

특히 ArrayIndexOutOfBoundsException 블록이 첫 번째 외부 try/catch 블록에 던져지면 fin 변수가 할당되지 않습니다. 외부 catch 블록에 return을 추가하면이 문제가 해결됩니다 : 장소에 return 문으로

try { 
    ... 
} catch(ArrayIndexOutOfBoundsException e){ 
    System.out.println("Array index out of bound exception"); 
    return; // <<== Here 
} 

을, 제어는 컴파일 타임 오류를 수정의 fin.read()fin하지 않는 한이 초기화되었습니다에 도달하지 않습니다.

+0

나는 그가 책에서 그대로 코드를 복사했는지 의심 스럽다. –

+0

@SotiriosDelimanolis 아마 맞을 것입니다. OP가'return' 문을 놓쳤을 가능성이 큽니다. – dasblinkenlight

+0

@Sotirios Delimanolis 및 @ dasblinkenlight 실수로 인해 유감입니다. 나는 try 블록 안에 fout을 초기화 한 후 "return"이라고 쓴 실수를했다. 그러나 나는 여기에 게시 한 후에 내 실수를 깨달았고 실수로 정말로 유감스럽게 생각합니다. –

1

이 문제를 해결하는 간단한 방법은 try 블록 내에 fin 및 fout이 필요한 작업을 수행하는 것입니다. 이렇게하면 스트림을 열지 못한 경우 스트림을 사용하지 않아도됩니다.

try 
{ 
    fout = new FileOutputStream(...); 
    fin = new FileInputStream(...); 

    // Code goes here 

    fout.close(); 
    fin.close(); 
} 
catch(FileNotFoundException e) 
{ 
    // Error code - e should contain the file name/path 
} 

또한, 당신이 그들을 선언 할 때 변수를 초기화하는 것이 좋습니다 항상 : 당신이 컴파일러 오류가 발생하지 않습니다 로직을 프로그래밍 (단지 null로 초기화하는) 그러나

FileOutputStream fout = null; 
FileInputStream fin = null; 

,이 방법은,하지만 경우 블록 처리를 시도하면 NullPointerExceptions가 올바르게 처리되지 않을 수 있습니다.

관련 문제