File transfer & File rename & Folder creation in java codes

来源:互联网 发布:包包淘宝店名起名大全 编辑:程序博客网 时间:2024/05/17 08:12
    public static void tranferFile(String fromPath, String toPath,String file) {

        InputStream inStream = null;
        OutputStream outStream = null;
        
        String name = "";
        if(file.indexOf(".")!=-1)
            name = file.substring(0,file.indexOf("."));
        
        
        File path = new File(toPath);
        if (!path.exists()){
            path.mkdirs();
        }

        try {
            File afile = new File(fromPath + file);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHMM");
            String destFile = name+"."+formatter.format(new java.util.Date());
            File bfile = new File(toPath + destFile);

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

            int length;
            if (afile.exists())
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, length);
                }
            
            inStream.close();
            outStream.close();
            
            String finalFile = name+".zip";
            boolean success = bfile.renameTo(new File(toPath + finalFile) );
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
原创粉丝点击