在这个快速教程中,我们将学习如何在Java中删除一个文件。
我们将看到在Java中删除一个文件的两种方法。
delete()
方法,从目录 "C://workspace "中删除 "sample.txt "文件delete()
method返回true
,当且仅当文件或目录被成功删除;false
否则。import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Java program demonstrates how to delete a file in Java.
* @author javaguides.net
*/
public class DeleteFileExample {
private static final Logger LOGGER = LoggerFactory
.getLogger(DeleteFileExample.class);
public static void main(String[] args) {
deleteFile();
}
public static void deleteFile() {
File file = new File("C://workspace/sample.txt");
if (file.delete()) {
LOGGER.info(file.getName() + "created !!");
} else {
LOGGER.info("Delete operation failed");
}
}
}
建议使用Java NIO的Files.delete()
方法来删除Java中的文件。
import java.io.IOException;
import java.nio.file.*;
public class DeleteFileExample {
public static void main(String[] args) throws IOException {
// File or Directory to be deleted
Path path = Paths.get("./demo.txt");
try {
// Delete file or directory
Files.delete(path);
System.out.println("File or directory deleted successfully");
} catch (NoSuchFileException ex) {
System.out.printf("No such file or directory: %s\n", path);
} catch (DirectoryNotEmptyException ex) {
System.out.printf("Directory %s is not empty\n", path);
} catch (IOException ex) {
System.out.println(ex);
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/07/how-to-delete-a-file-in-java.html
内容来源于网络,如有侵权,请联系作者删除!