来自文本文件的Java输入参数

时间:2013-04-06 05:03:56

标签: java

我想知道如何从命令行将数据从文本文件获取到java程序。我正在使用Windows。

我用过

Java myprogram < c:\inputfile.txt

它不起作用,但是当我使用

Java myprogram good

它有效。 'good'是我用它作为输入的词

仅供参考:当我使用

Java myprogram good > c:\outfile.txt

这是用于将输出写入文本文件..

我需要从文件文件“inputfile.txt”中读取并写入“outputfile.txt”

我用过这个

Java myprogram "c:\\inputfile.txt" > "c:\\outputfile.txt"

但没有工作

我使用它的代码

import edu.smu.tspell.wordnet.*;

public class myprogram{
public static void main (String [] args) {

System.setProperty("wordnet.database.dir", "C:\\Program Files (x86)\\WordNet\\2.1\\dict\\");
WordNetDatabase database = WordNetDatabase.getFileInstance();
      String result = "";
        NounSynset nounSynset;
        NounSynset[] hyponyms;
        Synset[] synsets = database.getSynsets(args[0]);

        for (int i = 0; i < synsets.length; i++) { //iteratre over all senses
            String[] wordForms = synsets[i].getWordForms();
            for (int j = 0; j < wordForms.length; j++) {
                System.out.println(wordForms[j]);
            }

} 

}
}

3 个答案:

答案 0 :(得分:2)

如果需要从文件中读取输入数据,则需要编写用于读取Java类中的文本文件的代码以进行读取。

您的代码似乎只是从命令行获取输入,而您正在将command line argument视为数据。

<强> See this example on how to read inputs from a text file.

答案 1 :(得分:0)

将值传递给双引号,如下所示:

Java myprogram good > "c:\\inputfile.txt"

答案 2 :(得分:0)

cmd下面只适用于unix flavor OS。

      java classfile > "/path/logfilename.log"

程序下面会读取文件并写入另一个文件  (您可以根据用例进行改进)

    public class ReadWriteFile {

        public static void main(String args[]) throws Exception {

        if (args.length == 0) {
            System.out.println("Enter the file name");
        } else {

            String fileName = args[0];

            BufferedReader input = new BufferedReader(new FileReader(fileName));

            String line = null;

            BufferedWriter writer = new BufferedWriter( new FileWriter( "output.txt"));

            try {
                while (( line = input.readLine()) != null){
                    System.out.println(line);
                    //or
                    writer.write(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(input != null) input.close();                
                if ( writer != null) writer.close( );
            }
        }
    }

}

对于逐字符阅读,请参阅以下内容 how-do-i-read-input-character-by-character-in-java