[英]Pass File From Command Line Java
So I have a file of integers, one in every line and I want to pass the file as input through args[0] from the command line.所以我有一个整数文件,每行一个,我想从命令行通过 args[0] 将文件作为输入传递。 When I write at the command line java Sorting input.txt I just get "input.txt".
当我在命令行 java Sorting input.txt 中写入时,我只得到“input.txt”。 But when I write java Sorting 3 2 6 i correctly get 2 3 6. How am I supposed to pass the file?
但是当我写 java 排序 3 2 6 时,我正确地得到 2 3 6。我应该如何传递文件? The code is below:
代码如下:
import java.util.Arrays;
public class Sorting {
public static void main (String args[])
{
Arrays.sort(args);
for(String num: args)
System.out.println(num);
}
} }
args[]
is just the list of arguments - if you pass in a file, the filename is the argument. args[]
只是 arguments 的列表——如果你传入一个文件,文件名就是参数。
Haven't run this, but try something like:还没有运行这个,但尝试类似的东西:
public static void main (String args[])
{
String filename = args[0];
// Read the file content to a String
String fileContent = Files.readString(Paths.get(filename));
// Split on whitespace (this is a regex, whitespace is \\s in Java - could also use " " for just space)
// The '+' here denotes "at least 1" whitespace character - added after the discussion below
String[] elements = fileContent.split("\\s+");
Arrays.sort(elements);
for(String num: args)
System.out.println(num);
}
== Edit== == 编辑==
If you want them sorted as integer's you're correct to say that the above treats them as String
s.如果您希望它们按整数排序,您说上面将它们视为
String
s 是正确的。 You need to parse them as Int
for that:为此,您需要将它们解析为
Int
:
public static void main (String args[]) {公共 static void main (String args[]) {
String filename = args[0];
// Read the file content to a String
String fileContent = Files.readString(Paths.get(filename));
// Split on whitespace (this is a regex, whitespace is \\s in Java - could also use " " for just space)
// The '+' here denotes "at least 1" whitespace character - added after the discussion below
String[] elements = fileContent.split("\\s+");
int[] intElements = new int[elements.length];
for (int i = 0; i < elements.length; i ++) {
try {
intElements[i] = Integer.parseInt(elements[i]);
} catch (NumberFormatException ex) {
System.err.println("Not a number: " + elements[i]);
}
}
Arrays.sort(intElements);
for(int num: intElements)
System.out.println(num);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.