[英]Java: How to read directory folder, count and display no of files and copy to another folder?
我必須讀取一個文件夾,計算文件夾中的文件數(可以是任何類型),顯示文件數,然后將所有文件復制到另一個文件夾(指定)。
我該怎么辦?
我必須讀取一個文件夾,計算文件夾中的文件數(可以是任何類型)顯示文件的數量
您可以在java.io.File
的javadocs中找到所有這些功能
然后將所有文件復制到另一個文件夾(指定)
這有點棘手。 閱讀: Java教程>讀取,編寫和創建文件 (請注意,其中描述的機制僅在Java 7或更高版本中可用。如果Java 7不是一個選項,請參考許多以前的類似問題之一,例如: 最快的一個: 最快寫文件的方法? )
你有這里的所有示例代碼:
http://www.exampledepot.com/egs/java.io/GetFiles.html
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
復制http://www.exampledepot.com/egs/java.io/CopyDir.html :
// Copies all files under srcDir to dstDir.
// If dstDir does not exist, it will be created.
public void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdir();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]));
}
} else {
// This method is implemented in Copying a File
copyFile(srcDir, dstDir);
}
}
然而這個東西很容易gooole :)
我知道這已經太晚了,但是下面的代碼對我有用。 它基本上遍歷目錄中的每個文件,如果找到的文件是一個目錄,那么它會進行遞歸調用。 它只提供目錄中的文件計數 。
public static int noOfFilesInDirectory(File directory) {
int noOfFiles = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
noOfFiles++;
}
if (file.isDirectory()) {
noOfFiles += noOfFilesInDirectory(file);
}
}
return noOfFiles;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.