2012-02-02 65 views
1

如果我從實際的命令行(即javac ...,java XXX.java(args [0])(args [1]))運行此命令,則以下代碼的行爲與預期相同。命令行參數從cmdline vs IDE

但是,如果我嘗試通過eclipse設置命令行參數,我會得到「輸入或輸出文件錯誤」錯誤,但如果cmd行參數在eclipse中lenght!= 2,我還會得到「必須指定輸入文件......」所以我知道它被賦予它們

有誰知道這筆交易有什麼用?

public class main { 

    public static Scanner fileScanner(String fName) throws FileNotFoundException { 
     return new Scanner(new FileInputStream(fName)); 
    } 

    public static PrintStream printStream(String fName) throws FileNotFoundException { 
     return new PrintStream(new FileOutputStream(fName)); 
    } 

    public static void main(String[] args) { 

     Scanner scan=null; 
    PrintStream out=null; 


    if(args.length != 2) { 
     System.out.println("Must specify input file & output file on cmd line"); 
     System.exit(0); 
    } 


    try { 
     scan = fileScanner(args[0]); 
     out = printStream(args[1]); 
    } catch(FileNotFoundException e) { 
     System.out.println("Error with input or output file"); 
     System.exit(0); 
    } 
+4

既然你正在傳遞的文件名,你絕對路徑傳遞?我懷疑eclipse正在使用與從命令行運行時不同的工作目錄,因此如果您傳遞的是相對路徑,它將無法找到該文件。 – Chris 2012-02-02 16:31:28

回答

0

我試過你的程序,它在eclipse中正常工作,當我給完整路徑的文件名。

package so.ch1; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.PrintStream; 
import java.util.Scanner; 

public class main { 

    /** 
    * @param args 
    */ 


     public static Scanner fileScanner(String fName) throws FileNotFoundException { 
       return new Scanner(new FileInputStream(fName)); 
       } 

     public static PrintStream printStream(String fName) throws FileNotFoundException { 
       return new PrintStream(new FileOutputStream(fName)); 
       } 


     public static void main(String[] args) { 

      Scanner scan=null; 
      PrintStream out=null; 


      if(args.length != 2) { 
       System.out.println("Must specify input file & output file on cmd line"); 
       System.exit(0); 
      } 


      try { 
       scan = fileScanner(args[0]); 
       out = printStream(args[1]); 
      } catch(FileNotFoundException e) { 
       System.out.println("Error with input or output file"); 
       System.exit(0); 
      } 

     } 
} 

args中給出了:F:/temp/abc.txt F:/temp/xyz.txt