Java中操作Linux命令实现文件传输(详细)
欢迎关注蚕豆公众号,不定时分享技术。同时欢迎加入蚕豆技术群哦,扫描公众号点击关于作者加群~~~~
一直想记录一下我这个文章的,但一直没想起来。之前做了一个java操作linux命令操作文件的东西,其实我当时也是百度,实际的代码其实就拿几行,希望能帮到大家!
java代码
public class ExcuteLinux {
private static final Logger logger = LoggerFactory.getLogger(ExcuteLinux.class);
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");
String path = df.format(new Date());
File file=new File(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));
++j;
break;
}
}
return path;
}
上述代码中呢除了红框内的代码,红框外的就不要管,那是我自己的逻辑
通过工具类的里的方法,参数就是要使用的命令,我这边使用的 cp 拷贝的命令,就可以实现文件之间的相互拷贝我其余的逻辑也就是获取文件名,什么的,大家根据自己需求来,但使用命令操作的就是,一个工具类,一个调用!
欢迎大家收看王不正讲技术,每年不知何时更新,大家随机等待哦!哈哈哈!每天记录一点,成长你我他哦!