简体   繁体   English

如何以编程方式删除linux中某个目录中存在的文件

[英]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? 有人可以让我知道是否还有另一种方法吗?

怎么样File#delete()

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.

相关问题 如何通过Java程序从Windows读取远程Linux目录中存在的文件属性? - How to read a file properties present in remote linux directory from windows through a java program? Java删除文件/目录,等同于linux“ rm -rf / tmp / garbagedir *” - Java delete file/directory equivalent of linux “rm -rf /tmp/garbagedir*” 如何以编程方式删除H2数据库文件? - How to delete a H2 database file programmatically? 如何以编程方式在一些JAR中搜索文件? - How to programmatically search for a file inside some JAR? 如何删除zip文件的内容而不删除目录 - How to delete the contents of the zip file but not the directory 如何删除目录中上传的相同文件? - how to delete the same file which is uploaded in a directory? 如何使用Java从目录中删除文件? - How to delete a file from a directory using Java? 如何在Spring中加载conf或resources目录下存在的任何文件 - How to load any file present under the conf or resources directory in Spring 如何将以前作为目录的文件更改回linux上的目录? - How to change a file that used to be a directory back to directory on linux? 如何在Linux环境中以编程方式突出显示(或选择)文件(或文件夹)(使用Java) - How to highlight (or select) a file (or folder) programmatically in Linux environment (using java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM