我目前正在开发一个项目,需要一些帮助。根据用户输入,我必须从一些 txt 文件中读取一些数据。程序的调用方式有以下三种:
java Graph [-u] -s start example_graph.txt
java Graph [-u] -a example_graph.txt
java Graph [-u] -d traffic.txt
根据用户选择的内容,我必须读取的文件是:
clrs.txt, traffic.txt, traffic_u.txt, facebook_combined_u.txt
我用来读取和存储文件数据的方法是
公共(public)无效readFile(){
String txtFile = "filename.csv";
BufferedReader br = null;
String line = "";
String txtSplitBy = ",";
try {
br = new BufferedReader(new FileReader(txtFile));
while ((line = br.readLine()) != null) {
String[] dj = line.split(txtSplitBy);
int node_a = Integer.parseInt(dj[0]);
int node_b = Integer.parseInt(dj[1]);
int weight = Integer.parseInt(dj[2]);
if (node_a > adj.size()) {
for (int i = adj.size() + 1; i <= node_a; i++) {
adj.add(new HashSet<Link>());
}
}
HashSet<Link> h = adj.get(node_a);
h.add(new Link(node_b, weight));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但此方法仅在我有特定文件作为输入时才有效。现在有多个文件,如何将文件名转换为字符串?
最佳答案
正如注释中指出的,您可以从 main 方法的 args 区域中的 cmd 行读取参数,例如:
public class SO {
public static void main(String[] args) {
for(String s : args){ //For each argument
if(s.indexOf(".") != -1){ //If contains a dot (like a file ext)
System.out.println(s); //print
}
}
}
}
运行时:
java SO [-u] -a example_graph.txt
它写出了文件的名称。
希望这有帮助!
关于java - 获取 cmd 中输入的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880136/