Java 如何修改main方法以从comandline获取输入和输出?
我想从命令行读取,而不是硬编码来读取Java 如何修改main方法以从comandline获取输入和输出?,java,eclipse,main,Java,Eclipse,Main,我想从命令行读取,而不是硬编码来读取infile和outfile。我该怎么做 /** * reads a file and creates a histogram from it * @param args string of argument * @precondition none */ public static void main(String[] args) { Histogram hist = new Histogram(); FileInputContro
infile
和outfile
。我该怎么做
/**
* reads a file and creates a histogram from it
* @param args string of argument
* @precondition none
*/
public static void main(String[] args) {
Histogram hist = new Histogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords("infile.txt");
output.writeWords("outfile.txt");
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
像这样运行程序:java YourClassName infle.txt outfile.txt
在main(String[]args)
中,args
是一个字符串数组,其中包含启动Java时传递的参数值
请务必阅读以便进一步阅读。要获得整数值,请像这样使用
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
要获取字符串,请使用此
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
对于输出,只需使用
System.out.println(“此处的文本”)代码>使用args
。类似于java helloworld.java file1.txt的内容
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();