【问题标题】:Command line args from cmdline vs in IDE命令行与 IDE 中的命令行参数
【发布时间】:2012-02-25 07:45:36
【问题描述】:

如果我从实际命令行运行以下代码(即 javac ...、java XXX.java (args[0]) (args[1])),则以下代码的行为符合预期。

但是,如果我尝试通过 Eclipse 设置命令行 args,我会收到“输入或输出文件错误”错误,但如果 eclipse 中的 cmd 行 args 长度!= 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);
    }

【问题讨论】:

  • 既然你在传递文件名,你是在传递绝对路径吗?我怀疑 Eclipse 使用的工作目录与您从命令行运行时使用的工作目录不同,因此如果您传入相对路径,它将无法找到该文件。

标签: java command-line command-line-arguments


【解决方案1】:

我试过你的程序,当我给出带有完整路径的文件名时,它在 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);
            }

        }
}

给定参数:F:/temp/abc.txt F:/temp/xyz.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-25
    • 2016-05-25
    • 2012-10-04
    • 2011-02-25
    • 2013-02-14
    相关资源
    最近更新 更多