是否有一种在Java应用程序中创建临时目录的标准且可靠的方法?Java的问题数据库中有一个条目,在评论中有一些代码,但我想知道是否有一个标准的解决方案可以在其中一个常见的库(Apache Commons等)中找到?
我希望我的应用程序的用户能够删除DCIM文件夹(位于SD卡上并包含子文件夹).
这有可能,如果是这样的话怎么样?
在Java中,我想删除包含文件和文件夹的文件夹中存在的所有内容.
public void startDeleting(String path) {
List<String> filesList = new ArrayList<String>();
List<String> folderList = new ArrayList<String>();
fetchCompleteList(filesList, folderList, path);
for(String filePath : filesList) {
File tempFile = new File(filePath);
tempFile.delete();
}
for(String filePath : folderList) {
File tempFile = new File(filePath);
tempFile.delete();
}
}
private void fetchCompleteList(List<String> filesList,
List<String> folderList, String path) {
File file = new File(path);
File[] listOfFile = file.listFiles();
for(File tempFile : listOfFile) {
if(tempFile.isDirectory()) {
folderList.add(tempFile.getAbsolutePath());
fetchCompleteList(filesList,
folderList, tempFile.getAbsolutePath());
} else {
filesList.add(tempFile.getAbsolutePath());
}
}
} …Run Code Online (Sandbox Code Playgroud) 枚举目录后,我现在需要删除所有文件.
我用了:
final File[] files = outputFolder.listFiles();
files.delete();
Run Code Online (Sandbox Code Playgroud)
但是这还没有删除目录.
我目前正在尝试以递归方式删除目录...奇怪的是,我能够找到的最短的代码是以下构造,采用ad-hoc内部类和访问者模式 ...
Path rootPath = Paths.get("data/to-delete");
try {
Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("delete file: " + file.toString());
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
System.out.println("delete dir: " + dir.toString());
return FileVisitResult.CONTINUE;
}
});
} catch(IOException e){
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
来源:这里
考虑到新的nioAPI消除了这么多的混乱和样板,这感觉非常笨拙和冗长......
有没有更短的方法来实现强制的递归目录删除?
我正在寻找纯本机Java 1.8方法,所以请不要链接到外部库...
尝试在Java中java.nio.file.DirectoryNotEmptyException递归删除从Delete目录中删除的递归删除方法中的偶然问题
代码(归功于@TrevorRobinson):
static void removeRecursive(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
logger.warn("Deleting " + file.getFileName());
Files.delete(file);
logger.warn("DELETED " + file.getFileName());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
// try to delete the file anyway, even if its attributes could
// not be read, since delete-only access is theoretically possible
// I NEVER SEE …Run Code Online (Sandbox Code Playgroud) 我必须删除超过30000张图像的文件夹.我在里面有'.nomedia'文件,以防止一直扫描.试图删除我必须检查每个文件的文件名的所有文件.如果我错过了这个检查 - '.nomedia'文件将被删除.如果在图像之前发生这种情况 - 这将导致很大的性能损失.不知道怎么解决这个问题?
有没有人知道如何在不使用'.nomedia'的情况下隐藏扫描图像?我可以使用假扩展保存文件,但我不确定这是否有效.
实际上测试显示了这个结果:检查名称使删除速度减慢约50%.问题不在检查代码中,而是在系统扫描文件夹中:(
当WatchService监视的目录被删除时,其父目录不会立即反映其文件的listFiles方法中的删除,并且无法删除.在明确停止整个服务之前,父母的后果似乎是:
为了演示,这个测试代码:
import java.io.*;
import java.nio.file.*;
class DirectoryTester {
static WatchService watcher;
static {
try{watcher = FileSystems.getDefault().newWatchService();}
catch (IOException e) {e.printStackTrace();}
}
public static void main(String[] args) throws IOException {
String SEPARATE = System.getProperty("file.separator");
String testDirName = System.getProperty("user.dir") + SEPARATE + "testDir";
String subDirName = testDirName + SEPARATE + "subDir";
String fileName = subDirName + SEPARATE +"aFile";
create(fileName);
Paths.get(subDirName).register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
delete(new File(testDirName));
}
static void create(String …Run Code Online (Sandbox Code Playgroud) 我正在尝试遍历文件树并删除所有文件/目录.代码如下:
Files.walkFileTree(metricPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) throws IOException {
if (exc == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw exc;
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
此代码在单元测试之间运行,每个单元测试都在表单中生成一个单独的文件folder1/folder2/file.当我尝试走这棵树时,DirectoryNotEmptyException当folder1试图被删除时抛出了它,尽管它显然是空的......
这是我试过的代码:
import java.io.*;
public class file03 {
public static void main(String[] args) {
File f1 = new File("C:/tempo1/tempo");
f1.mkdirs();
File f2 = new File("C:/test");
if(!f2.exists()) {
f2.mkdir();
}
f1 = new File("C:/tempo1/kempo");
f1.mkdirs();
f1 = new File("C:/tempo1");
String[] t = {};
if(f1.exists()) {
t = f1.list();
System.out.println(t.length + " files found");
}
for(int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
try {
Thread.sleep(3000);
}
catch(Exception e) {}
f2.delete();
f2 = new File("C:/tempo1/test.txt");
try {
f2.createNewFile();
}
catch(Exception …Run Code Online (Sandbox Code Playgroud) 下面的 Stream 表达式工作得很好:
Stream<String> s = Stream.of("yellow","blue", "white");
s.sorted(Comparator.reverseOrder())
.forEach(System.out::print);` //yellowwhiteblue
Run Code Online (Sandbox Code Playgroud)
为什么带有方法引用的等效方法无法编译?
s.sorted(Comparator::reverseOrder).forEach(System.out::print);
Run Code Online (Sandbox Code Playgroud)
Comparator 类型没有定义适用于此处的reverseOrder(String, String)
java ×8
directory ×6
file-io ×5
file ×4
nio ×3
android ×2
bluej ×1
comparator ×1
debugging ×1
delete-file ×1
filesystems ×1
io ×1
java-7 ×1
java-8 ×1
java-io ×1
java-stream ×1
windows ×1