最近用java寫了一個小工具,其中有一個操作是從android手機中pull文件夾到電腦上。在mac上調試一切正常,拿到windows上運行時發現會很大概率出現Process卡住的問題,原因不明。
后來將pull文件夾改為pull文件夾中的一個個文件后,不再出現卡住的問題。
卡住的代碼
private static void pullFiles(String remoteDir, String localDir) {
Utils.execute(String.format("%s pull %s %s", Utils.getAdbPath(), remoteDir, localDir));
}
運行正常的代碼
private static void pullFiles(String remoteDir, String localDir) {
List<String> fileNameList = Utils.getExecutionResult(String.format("%s shell ls %s", Utils.getAdbPath(), remoteDir));
for (String fileName : fileNameList) {
if (fileName != null) {
String filePath = dir + "/" + fileName;
Utils.execute(String.format("%s pull %s %s", Utils.getAdbPath(), file, new File(localDir, fileName).getAbsolutePath()));
}
}
}
工具代碼
public static List<String> getExecutionResult(String cmd) {
LOGGER.debug("get execution result cmd : {}", cmd);
ProcessBuilder builder = new ProcessBuilder();
if (SystemUtils.IS_OS_WINDOWS) {
builder.command("cmd", "/c", cmd);
} else {
builder.command("sh", "-c", cmd);
}
List<String> result = new LinkedList<>();
Thread t = new Thread(() -> {
BufferedReader outReader = null;
try {
Process p = builder.start();
outReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = outReader.readLine()) != null) {
LOGGER.debug("readline : {}", line);
result.add(line);
}
p.waitFor();
} catch (Exception e) {
LOGGER.error("occur exception", e);
} finally {
if (outReader != null) {
try {
outReader.close();
} catch (IOException e) {}
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {}
return result;
}
public static boolean execute(String cmd) {
LOGGER.debug("execute cmd : {}", cmd);
ProcessBuilder builder = new ProcessBuilder();
if (SystemUtils.IS_OS_WINDOWS) {
builder.command("cmd", "/c", cmd);
} else {
builder.command("sh", "-c", cmd);
}
try {
Process p = builder.start();
p.waitFor();
return true;
} catch (Exception e) {
LOGGER.error("occur exception", e);
return false;
}
}