[英]How to invoke a unix script from java?
我想刪除日志目錄中的舊日志文件。 要刪除超過6個月的日志文件,我編寫了如下腳本
查找/ dnbusr1 / ghmil / BDELogs / import -type f -mtime +120 -exec rm -f {} \\;
通過使用此腳本,我可以刪除舊文件,但是如何使用Java調用此腳本?
如果可移植性是一個問題,使您無法使用Runtime.exec()運行,那么使用Java使用File和FilenameFilter編寫此代碼非常簡單。
編輯:這是刪除目錄樹的靜態方法...您可以足夠容易地在過濾邏輯中添加:
static public int deleteDirectory(File dir, boolean slf) {
File[] dc; // directory contents
String dp; // directory path
int oc=0; // object count
if(dir.exists()) {
dir=dir.getAbsoluteFile();
if(!dir.canWrite()) {
throw new IoEscape(IoEscape.NOTAUT,"Not authorized to delete directory '"+dir+"'.");
}
dp=dir.getPath();
if(dp.equals("/") || dp.equals("\\") || (dp.length()==3 && dp.charAt(1)==':' && (dp.charAt(2)=='/' || dp.charAt(2)=='\\'))) {
// Prevent deletion of the root directory just as a basic restriction
throw new IoEscape(IoEscape.GENERAL,"Cannot delete root directory '"+dp+"' using IoUtil.deleteDirectory().");
}
if((dc=dir.listFiles())!=null) {
for(int xa=0; xa<dc.length; xa++) {
if(dc[xa].isDirectory()) {
oc+=deleteDirectory(dc[xa]);
if(!dc[xa].delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete directory '"+dc[xa]+"' - it may not be empty, may be in use as a current directory, or may have restricted access."); }
}
else {
if(!dc[xa].delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete file '"+dc[xa]+"' - it may be currently in use by a program, or have restricted access."); }
}
oc++;
}
}
if(slf) {
if(!dir.delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete directory '"+dir+"' - it may not be empty, may be in use as a current directory, or may have restricted access."); }
oc++;
}
}
return oc;
}
當您只想調用所描述的命令時,請調用:
Runtime r = Runtime.getRuntime();
Process process = r.exec("find /dnbusr1/ghmil/BDELogs/import -type f -mtime +120 -exec rm -f {} \\;"); //$NON-NLS-1$
process.waitFor();
如果要調用多個命令,請使用Chris Jester-Young答案。 exec方法還可以定義您要使用的文件。 其他答案鏈接方法描述。
添加到Crashworks的答案中,您可以在cmdarray
使用以下參數進行cmdarray
:
new String[] {"find", "/dnbusr1/ghmil/BDELogs/import", "-type", "f",
"-mtime", "+120", "-exec", "rm", "-f", "{}", ";"}
如果find
支持-exec ... {} +
語法,請更改";"
最后是"+"
。 這將使您的命令運行得更快(它將對一批文件一次調用rm
,而不是對每個文件一次調用rm
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.