一 查找一个目录下最大的文件名称(目录下有子目录)。
package CodeFile;
import java.io.*;
import java.util.*;
public class FindMaxFile {
private long maxFileSize;// 文件的最大值。
private String maxFileName = null;// 最大的文件名。
private Map<String, Long> fileMap = new HashMap<String, Long>();
public String findFile(File parentFile) {
if (parentFile.isDirectory()) {
// 获取该目录下的所有文件名或者目录名
String childFiles[] = parentFile.list();
for (int i = 0; i < childFiles.length; i++) {
String path = parentFile.getPath() + "/" + childFiles[i];
findFile(new File(path)); //递归调用
}
} else if (parentFile.isFile()) {
// 如果该路径是文件,获得它的字节数
long fileByteCount = parentFile.length();
//将文件名字和他的大小用键值对的形式放到fileMap容器中 fileMap.put(parentFile.getPath(), fileByteCount);
if (fileByteCount > maxFileSize) {
maxFileSize = fileByteCount;
maxFileName = parentFile.getPath();
System.out.println( "最大的所占字节数为:"+maxFileSize);
}
}
return maxFileName;
}
public void showFileMap() {
System.out.println(fileMap+ "\n");
}
public long getSize(){
return fileMap.size();
}
public static void main(String[] args) {
FindMaxFile fmf = new FindMaxFile();
File file = new File( "/home/randee/文档/a/b");//linux路径
System.out.println( "最大文件名为:"+fmf.findFile(file));
System.out.println( "文件个数为:"+fmf.getSize());
fmf.showFileMap();
}
}
import java.io.*;
import java.util.*;
public class FindMaxFile {
private long maxFileSize;// 文件的最大值。
private String maxFileName = null;// 最大的文件名。
private Map<String, Long> fileMap = new HashMap<String, Long>();
public String findFile(File parentFile) {
if (parentFile.isDirectory()) {
// 获取该目录下的所有文件名或者目录名
String childFiles[] = parentFile.list();
for (int i = 0; i < childFiles.length; i++) {
String path = parentFile.getPath() + "/" + childFiles[i];
findFile(new File(path)); //递归调用
}
} else if (parentFile.isFile()) {
// 如果该路径是文件,获得它的字节数
long fileByteCount = parentFile.length();
//将文件名字和他的大小用键值对的形式放到fileMap容器中 fileMap.put(parentFile.getPath(), fileByteCount);
if (fileByteCount > maxFileSize) {
maxFileSize = fileByteCount;
maxFileName = parentFile.getPath();
System.out.println( "最大的所占字节数为:"+maxFileSize);
}
}
return maxFileName;
}
public void showFileMap() {
System.out.println(fileMap+ "\n");
}
public long getSize(){
return fileMap.size();
}
public static void main(String[] args) {
FindMaxFile fmf = new FindMaxFile();
File file = new File( "/home/randee/文档/a/b");//linux路径
System.out.println( "最大文件名为:"+fmf.findFile(file));
System.out.println( "文件个数为:"+fmf.getSize());
fmf.showFileMap();
}
}
转载于:https://blog.51cto.com/randee/439072