目录分离算法(hashcode)

方法1.

public class FileUploadUtils {
    //目录分离算法
    public static String getRandomDirectory(String filename){
            int hashcode=filename.hashCode();
//          System.out.println(hashcode);
            
            //int类型数据在内存中占32位。转换成16进制数,就得到8个16进制数
            String hex=Integer.toHexString(hashcode);
            
//          System.out.println(hex);
            
            return "/"+hex.charAt(0)+"/"+hex.charAt(1);
            
    }
    
    public static void main(String[] args) {
        String path=getRandomDirectory("a.txt");
        
        File file=new File("d:/upload");
        
        File directory =new File(file,path);
        
        if(!directory.exists()){//如果不存在此目录就新建目录
            directory.mkdirs();
        }
    }
}

方法2.


public class FileUploadUtils {
    //目录分离算法
    public static String getRandomDirectory(String filename){

        int hashcode =filename.hashCode();
        System.out.println(Integer.toBinaryString(hashcode));
        int a =hashcode & 0xf;
        hashcode =hashcode>>>4;
        
        int b=hashcode &0xf;
        return "/"+a+"/"+b;
            
    }
    
    public static void main(String[] args) {
        String path=getRandomDirectory("a.txt");
        
        File file=new File("d:/upload");
        
        File directory =new File(file,path);
        
        if(!directory.exists()){//如果不存在此目录就新建目录
            directory.mkdirs();
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容