简体   繁体   English

除打印提示和扫描仪以外的用户输入

[英]User input other than print prompt and scanner

I wrote a program that asks for user input like this: 我写了一个程序,询问用户输入如下:

System.out.println("Where would you like the output file to end up? (full path and desired file name): ");
Scanner out_loc = new Scanner(System.in);
output_loc = out_loc.nextLine();

... ...

System.out.println("Hey, please write the full path of input file number " + i + "! ");
System.out.println("For example: /home/Stephanie/filein.txt");
Scanner fIn = new Scanner(System.in);

I ask several times for input in this way but it can get to be a huge pain if you mistype because then you have to kill the program and rerun. 我用这种方式多次询问输入,但是如果你错误输入会很麻烦,因为那时你必须杀死程序并重新运行。 Is there an easy way to just take input all at once when you run a program? 在运行程序时,有一种简单的方法可以一次性输入所有内容吗? As in just declaring it in the command line when having it run? 如何在运行时在命令行中声明它?

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?

You can use file redirection. 您可以使用文件重定向。

program < file

sends the file to the standard input of the program. 将文件发送到程序的标准输入。 In your case, 在你的情况下,

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere < file java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere <file

Or you can read from a file in your program. 或者您可以从程序中的文件中读取。 You can make this optional like 你可以选择这个

InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!

When you run the command as : 当您运行命令时:

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere? java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?

It runs the public static void main(String[] args) method of your primary class where you can get the userinputhere directly as: 它运行主类的public static void main(String[] args)方法,您可以直接获取userinputhere

  public static void main(String[] args)
     String userinputhere = args[0];
     ..... rest of your code
   }

If there are multiple user Inputs, you can get them all as : 如果有多个用户输入,您可以将它们全部作为:

  public static void main(String[] args)
      String userinput1 = args[0];
      String userinput2 = args[1];
      String userinput3 = args[2];
      //and so on..
      ..... rest of your code
  }

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

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