简体   繁体   English

通过命令行将文件输入Java

[英]Input file to java through command line

    public static void main(String[] args) throws IOException{          
            BufferedReader br = new BufferedReader(new FileReader("Input.txt"));
        }

I have to give input file through command line 我必须通过命令行输入文件

java -cp  Projectfile.java < Input.txt

what change should I do in my program to fetch this file in BufferedReader ? 我应该在程序中进行什么更改才能在BufferedReader获取此文件?

You pass it as command line argument 您将其作为命令行参数传递

java -cp  Projectfile.java Input.txt

and access passed argument in args[] 并访问args[]传递的参数

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

Try this way. 尝试这种方式。 You may optionally include 'else' part. 您可以选择包括“其他”部分。 If you dont want else part then move the bufferreader statement in 'then' part. 如果您不希望其他部分,则将“ buffertheer”语句移至“然后”部分。 Run it as -> 以->运行

java -cp . Projectfile Input.txt

Code -> 代码->

public static void main(String[] args) throws IOException, {      
        String file;    
        if ( args.length > 0 ) {
           file = args[0];
        }
        //Optionally you can define the file name if not supplied in java command. 
        else {
           file = "Input.txt"
        }

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

try the code below: 试试下面的代码:

public static void main(String [] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(args[0]));
}

During the execution of your program, you pass the file as argument but then you never use it. 在程序执行期间,您将文件作为参数传递,但随后再也不会使用它。 By using args[0], you will be using the argument that you passed on: 通过使用args [0],您将使用传递的参数:

java -cp  Projectfile.java < Input.txt

First of all after initialising the BufferedReader class with "br" as its object, you need to write the following line 首先以“ br”为对象初始化BufferedReader类后,需要编写以下行

String str=br.readLine();
System.out.println(str);

Next you have to create a file Input.txt and place it in the same folder as that of your java file. 接下来,您必须创建一个文件Input.txt并将其放置在与Java文件相同的文件夹中。

Next in the command prompt, write 接下来在命令提示符下编写

javac Projectfile.java
Press Enter
java -cp . Projectfile < Input.txt

In this way it'll be done. 这样就可以完成。 Happy Coding Journey!!! 快乐的编码之旅!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM