命令行参数作为java文件

时间:2013-07-20 19:56:43

标签: java

我试图在Eclipse中将java文件作为命令行arg传递。但是,每次都抛出FileNotFoundException并显示错误 - Product.java(系统无法找到指定的文件)。我将此Product文件与我的主java文件放在同一个包中。     还有一点需要提及,我正在使用FileReader。我的程序中BufferedReader来读取该文件。有什么我想念的吗?

package com.assign6.keyword.count;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CountKeywords {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String[] accessifiers = {"public", "protected", "private"};

        // Put each keyword in map with key
        Map<String, Integer> theKeyWordCount = new HashMap<String, Integer>();

        for( String str : accessifiers ){
            theKeyWordCount.put(str, 0);
            // Where str is key and 0 is value of Map
        }

        FileReader fr;
        BufferedReader br;
        File file = new File(args[0]);

        System.out.println(file);
        // Open and read the file

        try {

            fr = new FileReader(file);
            br = new BufferedReader(fr);

            String line;

            while( ( line = br.readLine() ) != null ){

                if( line.length() != 0 ){

                    if( theKeyWordCount.containsKey(line) ){

                        theKeyWordCount.put(line, theKeyWordCount.get(line)+1 );
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // File not found
            e.printStackTrace();

        } catch (IOException e) {
            // Not able to read line
            e.printStackTrace();
        }

        System.out.println(theKeyWordCount);

    }// end main method

}

2 个答案:

答案 0 :(得分:1)

  

我将此Product文件放在与我的主java文件相同的包中。

这不是真的相关。相反,当您运行程序时,您希望Product.java位于当前工作目录中。 (例如,如果您将程序作为java -jar path/to/program.jar运行,那么您需要Product.java位于包含path的文件夹中。)

答案 1 :(得分:0)

如果您尝试执行以下代码,并假设您的 CountKeywords 位于/home/username/javaProject文件夹中:

package com.assign6.keyword.count

public class CurrentDirectoryTest {
    public static void main(String[] args) {
        System.out.println("Working Directory = "
         + System.getProperty("user.dir"));
    }
}

你应该得到:

Working Directory = /home/username/javaProject

这意味着Java在javaProject内查找您的文件,而不是在

中查找
/home/username/javaProject/com/assign6/keyword/count

为了让你的班级工作,你需要:

  • 将文件移至/home/username/javaProject文件夹

  • 指定与javaProject相关的路径。在您的情况下,它意味着com/assign6/keyword/count/Product.java