处理文件同名问题:
方案一
* 文件名+uuid
* 进行分目录操作
[16:37]
文件上传目录分层------------
黑马程序员---------安卓
1今天上课,老师给我们讲解的知识扩展,说企业级OA系统,部署到企业一年后,发送邮件附件功能,不可以发送附加了。最后排错是因为,同一个文件夹中,子文件夹太多(子文件)夹中的文件太多问题。
这样在小的web项目中,也许不会发生,可以在大的企业级,频繁创建文件,中,会遇到这样的问题
解决方案是
1.文件名+uuid 来解决
uuid属于java.util 包下的工具类 可以随机生成一些32位的随机数字
2.使用file.hashcode后八位与上二进制来创建,不同的文件夹,我用的是与二进制,+右移4为进行 来进行组合,创建16*16文件夹
使用String 类行的hashCode方法来得到,传来文件名的hashcode码。使用hashcode码后八位与二进制进行与运算。得到1-15数字
在原来的基础上,右移4得到
进行上床目录分层的操作
http://blog.sina.com.cn/s/blog_439f80c40100n0hc.html java 左移动和右移动<转载>
1.file+File.separator 跨浏览器支持路径分隔符
2.file+file.mkdirs(); 创建多层文件
3. int d1=hashCode & 0xf;
int d2=hashCode>>>4 & 0xf;
eg:str.hashCode()-------->return int------------>int d1=hashCode & 0xf; 得到随机的15 个数字 -=------>int d2=hashCode>>>4 & 0xf ------->得到随机的15位,
-----15*15个不同的 文件夹
源码贴出来,我写的是工具类
package com.it.heima.uuidutils;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class Uuidutils {
public static String getUuid(String filename){
UUID uuid=new UUID(32, 32);
String newuid=uuid.randomUUID().toString();
System.out.println(newuid.replace("-", "")+"-"+filename);
return newuid.replace("-", "")+"-"+filename;
}
public static void main(String[] args) throws IOException {
//System.out.println(Uuidutils.ItemListener("hege.txt"));
}
/*public static String ItemListener(String filename){
if(filename==null)
{
return null;
}
int hashCode=filename.hashCode();
int d1=hashCode & 0xf;
int d2=hashCode>>>4 & 0xf;
return File.separator+d1+File.separator+d2+File.separator+filename;
}*/
public static String ItemListener(String dirPath,String filename) throws IOException{
if(filename==null)
{
return null;
}
int hashCode=filename.hashCode();
int d1=hashCode & 0xf;
int d2=hashCode>>>4 & 0xf;
String subpath= File.separator+d1+File.separator+d2; //中间目录
/**
* New 文件建立
*/
File file=new File(dirPath+subpath);
file.mkdirs();
// String zString=dirPath+subpath;
//交给主函数
File lastPath=new File(file+File.separator+filename);
System.out.println( lastPath.createNewFile());
return lastPath.toString();
}
}
封装的接口为
public static String ItemListener(String dirPath,String filename)
dirPath //文件上传的路径
filename //需要生成的文件名
//还可以扩展,让文件名+uuid的形式 这样完全解决了,
文件夹下子文件太多的瓶颈,解决了文件名重名的问题
// 写路径 得到上传的文件名字+文件要写的路径,web资源的位置
FileOutputStream fileOut = new FileOutputStream(new File(Uuidutils.ItemListener(dirPath, fileName)));
//FileOutputStream fileOut = new FileOutputStream(new File(dirPath,Uuidutils.ItemListener(fileName)));
byte[] buf = new byte[1024];
int len = -1;
while( (len = is.read(buf)) != -1 ){
fileOut.write(buf, 0, len);
}
企业级项目防止文件夹同问题解决方案,布布扣,bubuko.com
原文:http://blog.csdn.net/o279642707/article/details/22620581