2012-02-02 36 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