Java中操作Linux命令實作檔案傳輸(詳細)
一直想記錄一下我這個文章的,但一直沒想起來,之前做了一個java操作linux命令操作檔案的東西,其實我當時也是百度,實際的代碼其實就拿幾行,希望能幫到大家!
java代碼
/**
* 操作linux工具類
*/
public class ExcuteLinux {
private static final Logger logger = LoggerFactory.getLogger(ExcuteLinux.class);
/**
* 通過cp命令拷貝
*
* @param command
* @return
* @throws IOException
*/
public static String run(String command) throws IOException {
Scanner input = null;
String result = "";
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
try {
//等待命令執行完成
process.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
InputStream is = process.getInputStream();
input = new Scanner(is);
while (input.hasNextLine()) {
result += input.nextLine() + "\n";
}
result = command + "\n" + result; //加上命令本身,列印出來
logger.info("命令:" + result);
} finally {
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
}
return result;
}
}
這個是封了一個工具類,其中運用到的就是方法中Process類,大家可以下去自己看看這個類,通過這個類,專案上傳服務器后就可以直接操作檔案!還有一種方法是在本地專案啟動時操作linux命令,這個等我下篇文章嘍!
廢話太多了,趕緊言歸正傳
java 代碼
private String cpFile(List<String> param) throws IOException {
List<String> rename = renameFiles(param);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設定日期格式
// new Date()為獲取當前系統時間
String path = df.format(new Date());
File file=new File(customConfig.getRhTargetFileFolder() + path);
//ExcuteLinux.run("mkdir " + customConfig.getRhTargetFileFolder() + path); //創建檔案
createDirectoryQuietly(file);
for (int i = 0; i < param.size(); i++) {
for (int j = 0; j < rename.size(); j++) {
ExcuteLinux.run("cp -r " + param.get(i) + " " + customConfig.getRhTargetFileFolder() + path + "/" + rename.get(i));//在服務器上可執行的shell命令
++j;
break;
}
}
return path;
}
上述代碼中呢除了紅框內的代碼,紅框外的就不要管,那是我自己的邏輯

通過工具類的里的方法,引數就是要使用的命令,我這邊使用的 cp 拷貝的命令,就可以實作檔案之間的相互拷貝我其余的邏輯也就是獲取檔案名,什么的,大家根據自己需求來,但使用命令操作的就是,一個工具類,一個呼叫!

歡迎大家收看王不正講技術,每年不知何時更新,大家隨機等待哦!哈哈哈!每天記錄一點,成長你我他哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/22479.html
標籤:其他
上一篇:多重雙向鏈表實作LFU演算法
