【发布时间】:2021-12-10 16:10:30
【问题描述】:
我是这里的 Java 新手。 在我的程序中,我正在执行一个 shell 脚本,将其导出到一个 txt 文件并提取该 txt 文件的部分内容并打印出来。
我的代码如下
public static void Shell(String picture){
try {
File dir = new File("/usr/local/bin");
ProcessBuilder pb = new ProcessBuilder(new String[]{"/bin/bash", "-c", "./javatest.sh"});
pb.directory(dir);
pb.redirectOutput(new File("/usr/local/bin/" + picture + ".txt"));
Process start = pb.start();
start.getOutputStream();
pb.command("q\n");
start.destroy();
System.out.println("first line succeeded");
}catch (Exception e){
e.printStackTrace();
log.info("Error.Running.CMD");
}
try{
String format = MessageFormat.format("/usr/local/bin/{0}.txt", picture);
System.out.println("got file");
String line17 = Files.readAllLines(Paths.get(format)).get(16);
System.out.println("got line");
String subStr = line17.substring(5);
String line19 = Files.readAllLines(Paths.get("/usr/local/bin/" + picture +".txt")).get(18);
String pattern = "\\: (.*)"; // Capture everything after ':' colon character
String pattern2 = "(.*) \\:";
Pattern r = Pattern.compile(pattern);
Pattern r2 = Pattern.compile(pattern2);
Matcher m = r.matcher(line19);
Matcher m2 = r2.matcher(subStr);
if (m.find( ) && m2.find( )) {
System.out.println("Found value: " + m.group(1) );
System.out.println(m2.group(1));
}
}catch (IOException e) {
System.out.println("entry not found.");
}
}
当我运行这个测试用例时,我确实得到了我想要的 txt 文件,但根据日志,正确读取 txt 文件似乎有问题。
但是,当我将第二个 try/catch 部分复制到单独的测试文件时,它似乎可以正常工作。
public static void checkPrint(String picture){
try{
String format = MessageFormat.format("/usr/local/bin/{0}.txt", picture);
String line17 = Files.readAllLines(Paths.get(format)).get(16);
String subStr = line17.substring(5);
String line19 = Files.readAllLines(Paths.get("/usr/local/bin/" + picture +".txt")).get(18);
String pattern = "\\: (.*)"; // Capture everything after ':' colon character
String pattern2 = "(.*) \\:";
Pattern r = Pattern.compile(pattern);
Pattern r2 = Pattern.compile(pattern2);
Matcher m = r.matcher(line19);
Matcher m2 = r2.matcher(subStr);
if (m.find( ) && m2.find( )) {
System.out.println("Found value: " + m.group(1) );
System.out.println(m2.group(1));
}
}catch (IOException e) {
System.out.println("entry not found.");
}
}
我导入了相同的库,但我根本不明白为什么它可以在一个测试用例中工作,而不是在不同的测试文件中。
任何形式的反馈都将不胜感激。
提前谢谢你!
【问题讨论】:
标签: java testing text error-handling