我有一个小的Java程序,试图在命令行中传递文本文件和一个或多个用空格分隔的字符串。在文本文件中,我有一个软件包列表,如下所示:
gui -> awtui swingui swingui -> runner extensions textui -> runner
framework awtui -> runner runner -> framework extensions -> framework
现在在我的java中,我想通过在命令行中传递文本文件和package ame来列出每个软件包及其依赖项,如下所示:
$ java PackageList sample.txt gui swingui
当我按Enter键时,我想在控制台上列出每个程序包,如下所示:
gui -> awtui swingui
swingui -> runner extensions
如您所见,如果其他软件包未在命令行中作为参数传递,则它们不应出现在输出中。
这是我的Java代码,当前希望打印文件的所有内容,而不管文件名后面的命令行参数如何:
public class PackageList {
public static void main(String[] args) {
File inputFile = null;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(1);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inputFile));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
检查以下代码和注释:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PackageList {
public static void main(String[] args) {
File inputFile = null;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(1);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inputFile));
for(int i=1; i < args.length;i++){ // For loop to check - args[0] is file name so i = 1
boolean isDependencyExist = false; // check dependency
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.startsWith(args[i])){ // If file line starts with arg print
System.out.println(sCurrentLine);
isDependencyExist = true;
break;
}
}
if(!isDependencyExist){
System.out.println(args[i] + " ->");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句