Java:如何读取目录文件夹,计算并显示没有文件并复制到另一个文件夹?

我必须读取一个文件夹,计算文件夹中的文件数(可以是任何类型),显示文件数,然后将所有文件复制到另一个文件夹(指定)。

我该怎么办?

我必须读取一个文件夹,计算文件夹中的文件数(可以是任何类型)显示文件的数量

您可以在java.io.File的javadocs中找到所有这些function

然后将所有文件复制到另一个文件夹(指定)

这有点棘手。 阅读: Java教程>读取,编写和创建文件 (请注意,其中描述的机制仅在Java 7或更高版本中可用。如果Java 7不是一个选项,请参考许多以前的类似问题之一,例如: 最快的 : 最快写入文件的方式? )

你有这里的所有示例代码:

http://www.exampledepot.com

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 

复制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 

然而这个东西很容易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; }