2010-11-29 5 views
3

이것은 인터넷에서 파일의 행을 읽었을 때 발견 한 코드이며 이클립스를 사용하고 SanShin.txt로 파일 이름을 전달했습니다. 그것의 인수 필드. 하지만 인쇄됩니다 :파일을 명령 줄 인수로 전달하고 해당 줄을 읽습니다.

Error: textfile.txt (The system cannot find the file specified) 

코드 :이 오류를 인쇄하는 이유

public class Zip { 
    public static void main(String[] args){ 
     try{ 
      // Open the file that is the first 
      // command line parameter 
      FileInputStream fstream = new FileInputStream("textfile.txt"); 
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
      String strLine; 
      //Read File Line By Line 
      while ((strLine = br.readLine()) != null) { 
       // Print the content on the console 
       System.out.println (strLine); 
      } 
      //Close the input stream 
      in.close(); 
      }catch (Exception e){//Catch exception if any 
       System.err.println("Error: " + e.getMessage()); 
      } 


    } 
} 

저를 도와주세요. 감사합니다.

+0

나는 그런 텍스트 파일을 가지고! !! !! – user472221

+0

이것은 내 프로젝트의 위치입니다. C : \ Documents and Settings \ icc \ workspace \ Hoffman Project – user472221

+0

내 텍스트 파일은 바탕 화면에 있습니다. – user472221

답변

11
... 
// command line parameter 
if(argv.length != 1) { 
    System.err.println("Invalid command line, exactly one argument required"); 
    System.exit(1); 
} 

try { 
    FileInputStream fstream = new FileInputStream(argv[0]); 
} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

// Get the object of DataInputStream 
... 

> java -cp ... Zip \path\to\test.file 
+1

어떻게'argv'를 초기화해야합니까? 대신에'args'를 사용할 수 있습니까? – Navigatron

1

new FileInputStream("textfile.txt")이 맞습니다. 예외를 throw하는 경우 프로그램을 실행할 때 현재 디렉터리에 textfile.txt이 없습니다. 파일 이름이 실제로 testfile.txt이 아닌지 확인하십시오 (세 번째 위치에 x이 아니라 s에주의하십시오).


오프 주제 :하지만 당신의 이전 삭제 질문 (난 당신이, FWIW을 삭제하는 데 필요한 생각하지 않았다) 파일을 줄을 읽는 방법을 물었다. 당신은 아직 초보자이며 포인터를 사용하고 있습니다 : 은 이진 파일 용 FileInputStream을 사용하고 싶지만 java.ioReader 인터페이스/클래스 집합을 사용하십시오. ( FileReader 포함). 또한 가능한 경우 특정 클래스 (예 : FileReader r = ...이 아닌 Reader r = new FileReader("textfile.txt"))로 초기화 할 때도 인터페이스를 사용하여 변수를 선언하십시오.

1

"textfile.txt"을 지정하면 운영 체제는 해당 파일의 프로그램 작업 디렉토리를 검색합니다.

당신은 당신이 당신의 프로그램에서 실행중인 디렉토리를 알고 싶은 경우이 시도 new FileInputStream("C:\\full\\path\\to\\file.txt")

같은 것을 사용하여 파일의 절대 경로를 지정할 수 있습니다 System.out.println(new File(".").getAbsolutePath())

관련 문제