package lld;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class L4 {
public static String [] getFileName(String path)
{
File file = new File(path);
String [] fileName = file.list();
return fileName;
}
public static void getAllFileName(String path,ArrayList<String> fileName)
{
File file = new File(path);
File [] files = file.listFiles();
String [] names = file.list();
if(names != null)
fileName.addAll(Arrays.asList(names));
for(File a:files)
{
if(a.isDirectory())
{
getAllFileName(a.getAbsolutePath(),fileName);
}
}
}
public static void main(String[] args)
{
String [] fileName = getFileName("c:\\t");
for(String file:fileName)
{
System.out.println(file);
}
System.out.println("--------------------------------");
ArrayList<String> listFileName = new ArrayList<String>();
getAllFileName("c:\\t",listFileName);
for(String file:listFileName)
{
System.out.println(file);
}
}
}
package lld;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class L {
static List<File> fileList=null;
public static List<File> getFileList(String dirPath) {
File[] files = new File(dirPath).listFiles();
fileList = new ArrayList<File>();
for (File file : files) {
if(isTxtFile(file.getName())) {
fileList.add(file);
}
else if (file.isDirectory()){ //如果是文件夹,再调用自身
System.out.println(file);
//fileList.add(file);
getFileList(file.getAbsolutePath());
}
//fileList.add(file);
}
return fileList;
}
public static void main(String[] args)
{
getFileList("c:\\t");
System.out.println(fileList);
}
public static boolean isTxtFile(String fileName) {
if (fileName.lastIndexOf(".txt") > 0) {
return true;
}else if (fileName.lastIndexOf(".xls") > 0) {
return true;
}else if (fileName.lastIndexOf(".doc") > 0) {
return true;
}
else if (fileName.lastIndexOf(".pdf") > 0) {
return true;
}
else if (fileName.lastIndexOf(".docx") > 0) {
return true;
}
return false;
}
}