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

Java 除打印提示和扫描仪外的用户输入,java,user-input,Java,User Input,我编写了一个程序,要求用户输入如下内容: 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("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();

我以这种方式多次请求输入,但如果输入错误,可能会带来巨大的痛苦,因为这样你就必须终止程序并重新运行。当你运行一个程序时,有没有一种简单的方法可以一次获取所有的输入?就像让它运行时在命令行中声明它一样

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

您可以使用文件重定向

program < file
程序
将文件发送到程序的标准输入。就你而言

java-jar/home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar-userinputhere 也可以从程序中的文件中读取。您可以将其设置为可选的,如

InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!
InputStream in=args.length<1?System.in:新文件输入流(args[0]);
扫描仪扫描=新扫描仪(英寸);//只需创建一次扫描仪!

当您以以下方式运行命令时:

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

它运行主类的
publicstaticvoidmain(String[]args)
方法,您可以通过以下方式直接获取
userinputhere

  public static void main(String[] args)
     String userinputhere = args[0];
     ..... rest of your code
   }
如果有多个用户输入,您可以通过以下方式获取它们:

  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
  }

(或者)您可能有一个文件,并使用Scanner读取作为main方法中参数点的文件…因此在这种情况下,对于每个userinput(userinput1,userinput2),他们会在命令行上指定吗?像这样:java-jar/home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar-userinput1-userinput2-userinput3?@User:Yes。命令行中的所有输入都用
空格隔开
,无需前缀为
-
。好!我懂了。我要试试这个。多谢各位@用户:如果您认为这有帮助,请不要忘记接受答案。我不确定我是否理解。你能再解释一下吗?我想我的困惑点在于,我是直接在命令行中输入每个文件名,还是创建一个文件位置文件并将其传递给程序。您可以重定向文件的输入,或指定要加载的文件名,或指定要加载的文件目录,或指定要加载的文件名列表。这取决于你。我会做你认为最简单的事。
  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
  }