1.通过递归算法查找指定文件
public class FileSearch {
/**
* @Description: 测试该类
* @param args
*/
public static void main(String[] args) {
FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().equals("aa.xml");
}
};
List
for (File file : list) {
System.out.println(file.getName());
}
}
public static List
return search(new File(filePath), filter);
}
// 递归算法遍历指定文件
public static List
List
if (!file.exists()) {
return null;
}
if (file.isDirectory()) {
File[] subs = file.listFiles();
if (subs != null) {
for (File sub : subs) {
result.addAll(search(sub, filter));
}
}
}
if (filter.accept(file)) {
result.add(file);
}
return result;
}
}
2.通过递归算法删除指定文件
public class FileDelete {
//删除指定目录下以".txt"结尾的文件
public static void main(String...filter) {
deleteFile("./sjs/xml", new FileFilter(){
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
});
}
public static void deleteFile(String filePath,FileFilter filter) {
if(filePath == null || "".equals(filePath)) {
return ;
}
//如果过滤器为空,为了防止删去所有的文件,故不做删除操作
if(filter == null ) {
return ;
}
deleteFile(new File(filePath), filter) ;
}
private static void deleteFile(File file,FileFilter filter) {
if(!file.exists()) {
return ;
}
if(file.isDirectory()) {
File[] subs = file.listFiles(filter) ;
if(subs != null ) {
for(File sub : subs ) {
deleteFile(sub, filter) ;
}
}
}
if(filter.accept(file)) {
file.delete() ;
}
}
}
3.文件切割器
public class FileSplit {
public static void main(String...output) {
long start = System.currentTimeMillis() ;
split("C:\\fileparse\\nohup.out","C:\\logs",1024*1024*4L) ;
System.out.println(System.currentTimeMillis() - start) ;
}
public static void split(String source, String output, long capcity) {
File sourceFile = new File(source);
long length = sourceFile.length();
if (length <= 0) {
return;
}
if (capcity <= 0) {
capcity = 1024 * 1024L;
}
long size = (length % capcity == 0) ? length / capcity : length / capcity + 1;
InputStream is = null;
OutputStream out = null;
try {
is = new FileInputStream(sourceFile);
byte[] once = new byte[(int) capcity];
int readReally = 0;
for (int start = (int) size; start > 0; start--) {
try {
readReally = is.read(once);
byte[] really = new byte[readReally];
System.arraycopy(once, 0, really, 0, readReally);
out = new FileOutputStream(new File(output, sourceFile.getName()+"-" + start), false);
out.write(really);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}