[英]How to delete a file present in some directory in linux programmatically
My aim is to delete a file in some directory present in linux using a java program. 我的目的是使用Java程序删除Linux中存在的某些目录中的文件。 I have the following line that does that:
我有执行以下操作的以下行:
java.lang.Runtime.getRuntime().exec("/bin/rm -f " + fileToDelete.getAbsolutePath());
But I read that using linux commands from java program would be a costlier operation. 但是我读到,使用Java程序中的linux命令将是一个比较昂贵的操作。 Could anyone let me know if there is another way of doing this?
有人可以让我知道是否还有另一种方法吗?
boolean isFileDeleted = fileToDelete.delete();
You could use a File
object, as such: 您可以使用
File
对象,如下所示:
// initializes your file with your full path (or use your "fileToDelete" variable)
File file = new File("myFile");
// attempts to set the file writable and returns boolean result
System.out.println("Could set file writable: " + file.setWritable(true));
// attempts to delete the file and returns boolean result
System.out.println("Deleted succesfullly: " + file.delete());
Permission / delete operations may throw an unchecked SecurityException
. 权限/删除操作可能会引发未经检查的
SecurityException
。
if(file.exists())
boolean isSuccessful = file.delete();
Try this, it works in my Linux 试试这个,它可以在我的Linux中工作
File f= new File("Path");
try {
java.lang.Runtime.getRuntime().exec("rm -f " + f.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.