求目录的总大小
在开发中,难免会遇到与文件相关的操作,下面是我整理的,方便以后调用
根据路径path计算目录的总大小
public static long getFileSize(String path){
long sum = 0;
if (path != null){
File file = new File(path);
if (file.isFile()){
return file.length();
}else {
File[] files = file.listFiles();
for (File f : files) {
sum+=getFileSize(f.toString());
}
return sum;
}
}else {
return -1;
}
}
根据传入的文件对象计算目录的总大小
public static long fileSize(File file){
long len = 0;
if (file!= null){
if (file.isFile()){
return len = file.length();
}
else {
File[] files = file.listFiles();
for (File f : files) {
len+=fileSize(f);
}
}
return len;
}else {
return -1;
}
}
从文件中找出所需要的文件
方式一: 使用String 的 endsWith
public static void findFile(String path,String... regex) throws FileNotFoundException {
File file = new File(path);
if (file.exists()){
File[] files = file.listFiles();
for (File f : files) {
for (int i = 0; i < regex.length; i++) {
if (f.getName().endsWith(regex[i])){
System.out.println(f.getName());
}
}
}
}else {
throw new FileNotFoundException();
}
}
方式二: FilenameFilter
使用文件过滤器 FilenameFilter(匿名内部类)
public static void findFiles(String path,String... regex) {
File file = new File(path);
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
for (int i = 0; i < regex.length; i++) {
if (name.endsWith(regex[i])) {
return true;
}
}
return false;
}
});
for (File f : files) {
System.out.println(f.getName());
}
}
使用文件过滤器(实现FilenameFilter接口)
public class MyFilenameFilter implements FilenameFilter {
private File file;
private String suffex;
public MyFilenameFilter(File file, String suffex) {
this.file = file;
this.suffex = suffex;
}
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(suffex)){
return true;
}
return false;
}
}
public static void findFile1(File file,String regex){
MyFilenameFilter myFilenameFilter = new MyFilenameFilter(file,regex);
File[] files = file.listFiles(myFilenameFilter);
for (File f : files) {
System.out.println(f.getName());
}
}
删除指定目录下的所有文件
public static void deleteFile(String path) throws IOException {
File file = new File(path);
if (file.isFile()){
file.delete();
}else {
File[] files = file.listFiles();
for (File f : files) {
deleteFile(f);
}
}
file.delete();
}
上传文件
public static String FileUpload(HttpServletRequest req) {
String savepath = "";
Part part = null;
try {
part = req.getPart("file");
if (part!= null && part.getSize() > 0){
//原文件名字
String fileName = part.getSubmittedFileName();
//获取后缀名
int index = fileName.lastIndexOf(".");
String extname = fileName.substring(index);
String newName = UUID.randomUUID().toString().replace("-","")+extname;
//保存路径
savepath = "/uploads/"+newName;
//保存的物理地址
String realpath = req.getServletContext().getRealPath(savepath);
//保存文件
part.write(realpath);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
return savepath;
}