Java文件操作总结

//先写接口,可以对文件进行哪些操作即:创建新文件,删除文件 ,复制文件

public interface XfileInterface {

    
    /**
     * 删除文件或文件夹
     * @param path 文件夹完整绝对路径
     * @return
     */
    public void delete(String path) throws Exception;
    
    
    
    /**
     * 新建文件
     * @param path 文本文件完整绝对路径及文件名
     * @param delOldFile 是否删除旧的同名文件
     */
    public void createNewFile(String path,boolean delOldFile) throws Exception;

    
    
    /**
     * 新建文件
     * @param path 文本文件完整绝对路径及文件名
     * @param fileContent 文本文件内容
     */
    public void createNewFile(String path, String fileContent) throws Exception;
    
    
    /**
     * 新建文件
     * @param path 文本文件完整绝对路径及文件名
     * @return boolean是否存在
     */
    public boolean exists(String path) throws Exception;
    
    
    /**
     * 是否是文件夹
     * @param path 文件完整绝对路径
     * @return boolean是否是文件夹
     */
    public boolean isDirectory(String path) throws Exception;
    
    
    /**
     * 是否是文件
     * @param path 文件完整绝对路径及文件名
     * @return boolean是否是文件
     */
    public boolean isFile(String path) throws Exception;
    
    
    /**
     * 生成一个文件夹
     * @param path 文件夹完整绝对路径
     */
    public void mkdir(String path) throws Exception;
    
    
    /**
     * 生成一串 文件夹
     * @param path 文件夹完整绝对路径
     */
    public void mkdirs(String path) throws Exception;
    
    
    /**
     * 获取文件名
     * @param path 文件完整绝对路径及文件名
     * @return 文件名
     */
    public String getName(String path) throws Exception;
    
    
    /**
     * 获取文件名
     * @param path 文件完整绝对路径及文件名
     * @return 文件名
     */
    public String getParent(String path) throws Exception;
    
    
    /**
     * 复制单个文件
     * @param srcFilePath         准备复制的文件源
     * @param targerFilePath     拷贝到新绝对路径带文件名
     * @return
     */
    public void copyFile(String srcFilePath, String targerFilePath) throws Exception;
    
    
    /**
     * 复制整个文件夹的内容
     * @param oldFolderPath 准备拷贝的目录
     * @param newFolderPath 指定绝对路径的新目录
     * @return 被复制的文件夹的文件大小byte
     */
    public long copyFolder(String oldFolderPath, String newFolderPath) throws Exception;
    
    
    /**
     * 移动单个文件
     * @param srcFilePath         准备移动的文件源
     * @param targerFilePath     移动到新绝对路径带文件名
     * @return
     */
    public void moveFile(String srcFilePath, String targerFilePath) throws Exception;
    
    
    /**
     * 移动整个文件夹的内容
     * @param oldFolderPath 准备移动的目录
     * @param newFolderPath 移动的指定绝对路径
     */
    public void moveFolder(String oldFolderPath, String newFolderPath) throws Exception;
    
    
    /**
     * 返回InputStream,以便在需要读取文件的内容时获取该对象
     * @param path 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回InputStream
     */
    public java.io.InputStream getInputStream(String path) throws Exception;
    
    
    /**
     * 返回OputStream,以便在需要写入文件的内容时获取该对象
     * @param path 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回InputStream
     */
    public java.io.OutputStream getOutputStream(String path) throws Exception;
    
    
    /**
     * 查询磁盘剩余空间
     * @param path 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回磁盘剩余空间
     */
    public long getDiskFreeSpace(String path) throws Exception;
    
    /**
     * 保存上传文件到指定目录路径
     * @param dirPath 带有完整绝对路径的目录名
     * @param request HttpServletRequest
     * @param ActionForm form
     * @
     * @return 返回操作结果
     */
    //public String saveUploadFiles(String dirPath,HttpServletRequest request,ActionForm form);
    
    /**
     * 获取指定文件夹的子目录树节点数据
     * @param path 指定的目录
     * @return 子目录树节点数据
     */
    public TreeNode getDirectoryTreeNode(String path) throws Exception;
    
    /**
     * 获取指定文件的大小
     * @param path 指定的文件
     * @return 文件大小
     */
    public long getFileSize(String path) throws Exception;
    
    /**
     * 文件或目录重命名
     * @param srcPath 源文件完整绝对路径
     * @param targetPath 新的文件完整绝对路径
     * @return Boolean 成功删除返回true遭遇异常返回false
     */
    public boolean rename(String srcPath,String targetPath)throws Exception;

}

public class CommonXfile implements XfileInterface {
    
    private XfileInterface xfile;
    
    public static int LocalDiskXfileType = 1;
    public static int SmbXfileType = 2;
    
    public XfileInterface getXfile() {
        return xfile;
    }

    public void setXfile(XfileInterface xfile) {
        this.xfile = xfile;
    }

    /**
     * @param xfile类名
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public CommonXfile(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        // TODO 自动生成构造函数存根
        //return (XfileInterface) Class.forName(str).newInstance()
        this.setXfile((XfileInterface)Class.forName(className).newInstance());
    }
    
    /**
     * @param xfileType 整数,代表一种xfile类型:2或者CommonXfile.SmbXfileType 代表SmbXfile类,
     * 其他类型需要扩充
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public CommonXfile(int xfileType) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        // TODO 自动生成构造函数存根
        
        if(xfileType == 1)
        {
            this.setXfile(new LocalDiskXfile());
        }
        
        if(xfileType == 2)
        {
            this.setXfile(new SmbXfile());
        }
        
    }
    

    public void copyFile(String srcFilePath, String targerFilePath)
            throws Exception {
        // TODO 自动生成方法存根
        xfile.copyFile(srcFilePath, targerFilePath);
    }

    public long copyFolder(String oldFolderPath, String newFolderPath)
            throws Exception {
        // TODO 自动生成方法存根
        return xfile.copyFolder(oldFolderPath, newFolderPath);
    }

    public void createNewFile(String path, boolean delOldFile) throws Exception {
        // TODO 自动生成方法存根
        xfile.createNewFile(path, delOldFile);
    }

    public void createNewFile(String path, String fileContent) throws Exception {
        // TODO 自动生成方法存根
        xfile.createNewFile(path, fileContent);
    }

    public void delete(String path) throws Exception {
        // TODO 自动生成方法存根
        xfile.delete(path);
    }

    public boolean exists(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.exists(path);
    }

    public long getDiskFreeSpace(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getDiskFreeSpace(path);
    }

    public InputStream getInputStream(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getInputStream(path);
    }

    public String getName(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getName(path);
    }

    public OutputStream getOutputStream(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getOutputStream(path);
    }

    public String getParent(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getParent(path);
    }

    public boolean isDirectory(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.isDirectory(path);
    }

    public boolean isFile(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.isFile(path);
    }

    public void mkdir(String path) throws Exception {
        // TODO 自动生成方法存根
        xfile.mkdir(path);
    }

    public void mkdirs(String path) throws Exception {
        // TODO 自动生成方法存根
        xfile.mkdirs(path);
    }

    public void moveFile(String srcFilePath, String targerFilePath)
            throws Exception {
        // TODO 自动生成方法存根
        xfile.moveFile(srcFilePath, targerFilePath);
    }

    public void moveFolder(String oldFolderPath, String newFolderPath)
            throws Exception {
        // TODO 自动生成方法存根
        xfile.moveFolder(oldFolderPath, newFolderPath);
    }

    /**
     * 保存上传文件到指定目录路径
     * @param dirPath 带有完整绝对路径的目录名
     * @param request HttpServletRequest
     * @param ActionForm form
     * @
     * @return 返回操作结果
     */
    public String saveUploadFiles(String dirPath, HttpServletRequest request,ActionForm form)throws Exception {
        // TODO 自动生成方法存根
        String result = "SUCCESS";
        List filepathList = new ArrayList();
//        已经上次文件的大小
        long uploadedFileSize = 0;
        request.getSession().setAttribute("uploadedFileSize", new Long(uploadedFileSize));
        
        String MATERIALPLANID = request.getParameter("MATERIALPLANID");    //物料计划单ID
        String STOCKID = request.getParameter("STOCKID");    //物料采购单ID
        
        try {
    //        如果文挡存储目录不存在,则生成目录
            if(!xfile.exists(dirPath))
            {
                xfile.mkdirs(dirPath);
            }else if(xfile.exists(dirPath) && xfile.isFile(dirPath))
            {
    //            如果有和当前目录同名的文件
                return "DIR_HAS_SAME_FILE_EXIST";
            }
    
    //        计算上传的所有文件的大小
            Hashtable fileh = form.getMultipartRequestHandler().getFileElements();
            
            long allUpFileSize = 0;
            for (Enumeration e = fileh.keys(); e.hasMoreElements();)
            {
                String key = (String) e.nextElement();
    
                FormFile formfile = (FormFile) fileh.get(key);
                allUpFileSize += formfile.getFileSize();
                
            }
            request.getSession().setAttribute("allUpFileSize", new Long(allUpFileSize));
            request.getSession().setAttribute("allUpFileCount", new Long(fileh.size()));
            
    //        磁盘剩余可用空间
            long freeSpace = xfile.getDiskFreeSpace(dirPath);
            
            if(freeSpace<allUpFileSize)
            {
    //            如果磁盘空间不足
                return "LACKSPACE";
            }
            
            String filename = "";
            String filePath ="";
            long filesize = 0;
//            已经上传文件的个数
            int uploadedFileCount = 0;
//            存储上传的所有文件            
            for (Enumeration e = fileh.keys(); e.hasMoreElements();)
            {                
                String key = (String) e.nextElement();

                FormFile formfile = (FormFile) fileh.get(key);
                filename = formfile.getFileName().trim(); // 文件名
                //added by lmr2012-10-31 15:56:17 用于物料升级后再采购环节增加的上传附件功能
                if((MATERIALPLANID != null && !MATERIALPLANID.equals("")) && (STOCKID != null && !STOCKID.equals(""))){
                    filename = STOCKID + "_" + formfile.getFileName().trim();
                    request.setAttribute("accname", formfile.getFileName().trim());
                    request.setAttribute("accpath", "/upload/matstoragefile/"+filename);
                }
                
                if(!filename.equals(""))
                {
                filesize = formfile.getFileSize();
                filePath = dirPath + "/" + filename;
                filepathList.add(filePath);
                
                uploadedFileCount++;
                request.getSession().setAttribute("uploadedFileCount", new Long(uploadedFileCount));
                request.getSession().setAttribute("uploadingFileName", filename);
                request.getSession().setAttribute("uploadingFileSize", new Long(filesize));
                
                
                // 文件读入
                InputStream stream = formfile.getInputStream();
                
                // 建立一个上传文件的输出流(写)
                OutputStream bos = xfile.getOutputStream(filePath);
                int bytesRead = 0;
                byte[] buffer = new byte[102400];
                // 将文件写入服务器
                while ((bytesRead = stream.read(buffer, 0, 102400)) != -1)
                {
                    bos.write(buffer, 0, bytesRead);
                    
                    //累计已经上传的文件的大小
                    uploadedFileSize += bytesRead;
                    request.getSession().setAttribute("uploadedFileSize", new Long(uploadedFileSize));
                }
                }
                
            }
                
            return result;
        
        } catch (Exception e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
            
            //上传出错后,删除已经上传文件
            for(int i=0; i<filepathList.size(); i++)
            {
                String path = (String)filepathList.get(i);
                try {
                    xfile.delete(path);
                } catch (Exception e1)
                {
                    // TODO 自动生成 catch 块
                    e1.printStackTrace();
                    throw e1;
                }
            }
            throw e;
            //return "FAIL";
        }
    }

    
    /**
     * 以指定的文件名下载文件
     * @param filepath 带有完整绝对路径
     * @param fileName 指定的文件名
     * @param request
     * @param response
     * @throws Exception
     */
    public void downloadFile(String filepath,String fileName,HttpServletRequest request, HttpServletResponse response)throws Exception {
        
        response.setContentType("application/octet-stream; charset=GBK");
        response.setHeader("accept-ranges", "bytes");
        
        String filename = fileName;
        if (filename.length() > 150) {
            String guessCharset = request.getCharacterEncoding();/*根据request的locale 得出可能的编码,中文操作系统通常是gb2312*/
            filename = new String(filename.getBytes(guessCharset), "ISO8859-1");
        }
        
        if(xfile.exists(filepath))
        {
            //下面的参数filename是下载保存时的文件名
            response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "utf-8"));
            ServletOutputStream os = response.getOutputStream();
            //FileInputStream in = new FileInputStream(filepath);
            InputStream in = xfile.getInputStream(filepath);
            byte[] bytes = new byte[20480];
            int size = 0;
            while ((size = in.read(bytes)) != -1)
            {
                os.write(bytes, 0, size);
            }
            
            in.close();
            os.flush();
            os.close();
        }
    }
    

    /**
     * 下载文件
     * @param filepath 带有完整绝对路径
     * @param HttpServletResponse response
     */
    public void downloadFile(String filepath,HttpServletRequest request, HttpServletResponse response)throws Exception {
        
        int index = filepath.lastIndexOf("\\");
        if(index == -1)
        {
            index = filepath.lastIndexOf("/");
        }
        String filename = filepath.substring(index+1);
        this.downloadFile(filepath, filename, request, response);
    }
    
    
    /**
     * copy多个文件文件到指定目录路径
     * @param filePathList 需要copy的file相对路径
     * @param targetDirPath 带有完整绝对路径的目录名
     * @param docuLibUpBackupUrl 上传文件服务器的文档库备份url
     * @param request HttpServletRequest
     * @
     * @return 返回操作结果
     */
    public String copyFiles(List filePathList,String targetDirPath,String docuLibUpBackupUrl, HttpServletRequest request)throws Exception {
        // TODO 自动生成方法存根
        String result = "SUCCESS";
        List didfilepathList = new ArrayList();
//        已经上次文件的大小
        long uploadedFileSize = 0;
        request.getSession().setAttribute("uploadedFileSize", new Long(uploadedFileSize));
        
        try {
    //        如果文挡存储目录不存在,则生成目录
            if(!xfile.exists(targetDirPath))
            {
                xfile.mkdirs(targetDirPath);
            }else if(xfile.exists(targetDirPath) && xfile.isFile(targetDirPath))
            {
    //            如果有和当前目录同名的文件
                return "DIR_HAS_SAME_FILE_EXIST";
            }
    
    //        计算上传的所有文件的大小
            //Hashtable fileh = form.getMultipartRequestHandler().getFileElements();
            
            long allUpFileSize = 0;
            for (int i=0; i<filePathList.size(); i++)
            {
                long filesize = xfile.getFileSize(docuLibUpBackupUrl + (String)filePathList.get(i));
                allUpFileSize += filesize;
                
            }
            request.getSession().setAttribute("allUpFileSize", new Long(allUpFileSize));
            request.getSession().setAttribute("allUpFileCount", new Long(filePathList.size()));
            
    //        磁盘剩余可用空间
            long freeSpace = xfile.getDiskFreeSpace(targetDirPath);
            
            if(freeSpace<allUpFileSize)
            {
    //            如果磁盘空间不足
                return "LACKSPACE";
            }
            
            String filename = "";
            String filePath ="";
            long filesize = 0;
//            已经copy文件的个数
            int uploadedFileCount = 0;
//            copy所有文件            
            for (int i=0; i<filePathList.size(); i++)
            {
                String relativeFilePaht = (String) filePathList.get(i);
                String srcFilePath = docuLibUpBackupUrl + relativeFilePaht;
                int index = 0;
                index = srcFilePath.lastIndexOf("\\");
                if(index == -1)
                {
                    index = srcFilePath.lastIndexOf("/");
                }
                filename = srcFilePath.substring(index+1).trim(); // 文件名
                
                filesize = xfile.getFileSize(srcFilePath);
                if(targetDirPath.endsWith("/"))
                {
                    filePath = targetDirPath + relativeFilePaht;
                }else
                {
                    filePath = targetDirPath + "/" + relativeFilePaht;
                }
                
                didfilepathList.add(filePath);
                
                uploadedFileCount++;
                request.getSession().setAttribute("uploadedFileCount", new Long(uploadedFileCount));
                request.getSession().setAttribute("uploadingFileName", filename);
                request.getSession().setAttribute("uploadingFileSize", new Long(filesize));
                
                if(xfile.exists(srcFilePath))
                {
//                     文件读入
                    InputStream stream = xfile.getInputStream(srcFilePath);
                    
                    // 建立一个目标文件的输出流(写)
                    OutputStream bos = xfile.getOutputStream(filePath);
                    int bytesRead = 0;
                    byte[] buffer = new byte[102400];
                    // copy文件
                    while ((bytesRead = stream.read(buffer, 0, 102400)) != -1)
                    {
                        bos.write(buffer, 0, bytesRead);
                        
                        //累计已经copy的文件的大小
                        uploadedFileSize += bytesRead;
                        request.getSession().setAttribute("uploadedFileSize", new Long(uploadedFileSize));
                    }
                }
            }
                
            return result;
        
        } catch (Exception e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
            
            //上传出错后,删除已经上传文件
            for(int i=0; i<didfilepathList.size(); i++)
            {
                String path = (String)didfilepathList.get(i);
                try {
                    xfile.delete(path);
                } catch (Exception e1)
                {
                    // TODO 自动生成 catch 块
                    e1.printStackTrace();
                    throw e1;
                }
            }
            throw e;
            //return "FAIL";
        }
    }
    
    
    /**
     * copy多个文件文件到指定目录路径
     * @param filePathList 需要copy的file路径
     * @param targetDirPath 带有完整绝对路径的目录名
     * @param request HttpServletRequest
     * @
     * @return 返回操作结果
     */
    public String copyFiles(List filePathList,String targetDirPath, HttpServletRequest request)throws Exception {
        // TODO 自动生成方法存根
        String result = "SUCCESS";
        List didfilepathList = new ArrayList();
//        已经上次文件的大小
        long uploadedFileSize = 0;
        request.getSession().setAttribute("uploadedFileSize", new Long(uploadedFileSize));
        
        try {
    //        如果文挡存储目录不存在,则生成目录
            if(!xfile.exists(targetDirPath))
            {
                xfile.mkdirs(targetDirPath);
            }else if(xfile.exists(targetDirPath) && xfile.isFile(targetDirPath))
            {
    //            如果有和当前目录同名的文件
                return "DIR_HAS_SAME_FILE_EXIST";
            }
    
    //        计算上传的所有文件的大小
            //Hashtable fileh = form.getMultipartRequestHandler().getFileElements();
            
            long allUpFileSize = 0;
            for (int i=0; i<filePathList.size(); i++)
            {
                long filesize = xfile.getFileSize((String)filePathList.get(i));
                allUpFileSize += filesize;
                
            }
            request.getSession().setAttribute("allUpFileSize", new Long(allUpFileSize));
            request.getSession().setAttribute("allUpFileCount", new Long(filePathList.size()));
            
    //        磁盘剩余可用空间
            long freeSpace = xfile.getDiskFreeSpace(targetDirPath);
            
            if(freeSpace<allUpFileSize)
            {
    //            如果磁盘空间不足
                return "LACKSPACE";
            }
            
            String filename = "";
            String filePath ="";
            long filesize = 0;
//            已经copy文件的个数
            int uploadedFileCount = 0;
//            copy所有文件            
            for (int i=0; i<filePathList.size(); i++)
            {
                String srcFilePath = (String) filePathList.get(i);
                int index = 0;
                index = srcFilePath.lastIndexOf("\\");
                if(index == -1)
                {
                    index = srcFilePath.lastIndexOf("/");
                }
                filename = srcFilePath.substring(index+1).trim(); // 文件名
                
                filesize = xfile.getFileSize(srcFilePath);
                if(targetDirPath.endsWith("/"))
                {
                    filePath = targetDirPath + filename;
                }else
                {
                    filePath = targetDirPath + "/" + filename;
                }
                
                didfilepathList.add(filePath);
                
                uploadedFileCount++;
                request.getSession().setAttribute("uploadedFileCount", new Long(uploadedFileCount));
                request.getSession().setAttribute("uploadingFileName", filename);
                request.getSession().setAttribute("uploadingFileSize", new Long(filesize));
                
                if(xfile.exists(srcFilePath))
                {
//                     文件读入
                    InputStream stream = xfile.getInputStream(srcFilePath);
                    
                    // 建立一个目标文件的输出流(写)
                    OutputStream bos = xfile.getOutputStream(filePath);
                    int bytesRead = 0;
                    byte[] buffer = new byte[102400];
                    // copy文件
                    while ((bytesRead = stream.read(buffer, 0, 102400)) != -1)
                    {
                        bos.write(buffer, 0, bytesRead);
                        
                        //累计已经copy的文件的大小
                        uploadedFileSize += bytesRead;
                        request.getSession().setAttribute("uploadedFileSize", new Long(uploadedFileSize));
                    }
                }
            }
                
            return result;
        
        } catch (Exception e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
            
            //上传出错后,删除已经上传文件
            for(int i=0; i<didfilepathList.size(); i++)
            {
                String path = (String)didfilepathList.get(i);
                try {
                    xfile.delete(path);
                } catch (Exception e1)
                {
                    // TODO 自动生成 catch 块
                    e1.printStackTrace();
                    throw e1;
                }
            }
            throw e;
            //return "FAIL";
        }
    }
    
    
    /**
     * copy多个文件文件到指定目录路径
     * @param filePathList 需要copy的file路径
     * @param targetDirPath 带有完整绝对路径的目录名
     * @param request HttpServletRequest
     * @
     * @return 返回操作结果
     */
    public String copyFiles(List filePathList,String targetDirPath)throws Exception {
        // TODO 自动生成方法存根
        String result = "SUCCESS";
        List didfilepathList = new ArrayList();
        try {
    //        如果文挡存储目录不存在,则生成目录
            if(!xfile.exists(targetDirPath))
            {
                xfile.mkdirs(targetDirPath);
            }else if(xfile.exists(targetDirPath) && xfile.isFile(targetDirPath))
            {
    //            如果有和当前目录同名的文件
                return "DIR_HAS_SAME_FILE_EXIST";
            }
    
    //        计算上传的所有文件的大小
            //Hashtable fileh = form.getMultipartRequestHandler().getFileElements();
            
            long allUpFileSize = 0;
            for (int i=0; i<filePathList.size(); i++)
            {
                long filesize = xfile.getFileSize((String)filePathList.get(i));
                allUpFileSize += filesize;
                
            }
            
    //        磁盘剩余可用空间
            long freeSpace = xfile.getDiskFreeSpace(targetDirPath);
            
            if(freeSpace<allUpFileSize)
            {
    //            如果磁盘空间不足
                return "LACKSPACE";
            }
            
            String filename = "";
            String filePath ="";
//            已经copy文件的个数
//            copy所有文件            
            for (int i=0; i<filePathList.size(); i++)
            {
                String srcFilePath = (String) filePathList.get(i);
                int index = 0;
                index = srcFilePath.lastIndexOf("\\");
                if(index == -1)
                {
                    index = srcFilePath.lastIndexOf("/");
                }
                filename = srcFilePath.substring(index+1).trim(); // 文件名
                
                if(targetDirPath.endsWith("/"))
                {
                    filePath = targetDirPath + filename;
                }else
                {
                    filePath = targetDirPath + "/" + filename;
                }
                
                didfilepathList.add(filePath);
                
                if(xfile.exists(srcFilePath))
                {
                    xfile.copyFile(srcFilePath, filePath);
                }
                
            }
                
            return result;
        
        } catch (Exception e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
            
            //上传出错后,删除已经上传文件
            for(int i=0; i<didfilepathList.size(); i++)
            {
                String path = (String)didfilepathList.get(i);
                try {
                    xfile.delete(path);
                } catch (Exception e1)
                {
                    // TODO 自动生成 catch 块
                    e1.printStackTrace();
                    throw e1;
                }
            }
            throw e;
            //return "FAIL";
        }
    }
    
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO 自动生成方法存根
        CommonXfile cxf = new CommonXfile("ht.xfile.SmbXfile");
        List filePathList = new ArrayList();
        filePathList.add("smb://smbtest:smbtest@192.168.1.253/doclib/档案2\\ffff.tar.gz");
        filePathList.add("smb://smbtest:smbtest@192.168.1.253/doclib/档案2/档案21\\20081006南热电物料系统改进设计02.doc");
        filePathList.add("smb://smbtest:smbtest@192.168.1.253/doclib/档案2\\iii.rar");
        String targetDirPath = "smb://smbtest:smbtest@192.168.1.253/doclibbak";
        cxf.copyFiles(filePathList, targetDirPath);
        
    }
    
    /**
     * 获取指定文件夹的子目录树节点数据
     * @param path 指定的目录
     * @return 子目录树节点数据
     */
    public TreeNode getDirectoryTreeNode(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getDirectoryTreeNode(path);
    }

    public long getFileSize(String path) throws Exception {
        // TODO 自动生成方法存根
        return xfile.getFileSize(path);
    }

    public boolean rename(String srcPath, String targetPath) throws Exception {
        // TODO 自动生成方法存根
        return xfile.rename(srcPath, targetPath);
    }
    
    
}

public class SmbXfile implements XfileInterface {
    
    private SmbFileOperate sfo = new SmbFileOperate();
    
    public SmbXfile() {
        // TODO 自动生成构造函数存根
    }

    public void copyFile(String srcFilePath, String targerFilePath)
            throws Exception {
        // TODO 自动生成方法存根
        sfo.copyFile2(srcFilePath, targerFilePath);
    }

    public long copyFolder(String srcFolderPath, String targetFolderPath)
            throws Exception {
        // TODO 自动生成方法存根
        return sfo.copyFolder(srcFolderPath, targetFolderPath);
    }

    public void createNewFile(String path, boolean delOldFile) throws Exception {
        // TODO 自动生成方法存根

    }

    public void createNewFile(String path, String fileContent) throws Exception {
        // TODO 自动生成方法存根
        sfo.createFile(path, fileContent);
    }

    public void delete(String path) throws Exception {
        // TODO 自动生成方法存根
        sfo.delete(path);
    }

    public boolean exists(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.exists(path);
    }

    public InputStream getInputStream(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getInputStream(path);
    }

    public String getName(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getName(path);
    }

    public String getParent(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getParent(path);
    }

    public boolean isDirectory(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.isDirectory(path);
    }

    public boolean isFile(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.isFile(path);
    }

    public void mkdir(String path) throws Exception {
        // TODO 自动生成方法存根
        sfo.createFolder(path);
    }

    public void mkdirs(String path) throws Exception {
        // TODO 自动生成方法存根
        sfo.createFolders(path);
    }

    public void moveFile(String srcFilePath, String targerFilePath)
            throws Exception {
        // TODO 自动生成方法存根
        sfo.moveFile(srcFilePath, targerFilePath);
    }

    public void moveFolder(String oldFolderPath, String newFolderPath)
            throws Exception {
        // TODO 自动生成方法存根
        sfo.moveFolder(oldFolderPath, newFolderPath);
    }

    public OutputStream getOutputStream(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getOutputStream(path);
    }

    public long getDiskFreeSpace(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getDiskFreeSpace(path);
    }

    public TreeNode getDirectoryTreeNode(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getDirectoryTreeNode(path);
    }

    public long getFileSize(String path) throws Exception {
        // TODO 自动生成方法存根
        return sfo.getFileSize(path);
    }

    public boolean rename(String srcPath, String targetPath) throws Exception {
        // TODO 自动生成方法存根
        return sfo.rename(srcPath, targetPath);
    }

}
/**
 * SMB file 操作类,利用SMBfile远程操作共享文件
 * @author Administrator
 *
 */
public class SmbFileOperate {
    /**
     * @param args
     */
    private String message;
    public SmbFileOperate() {
         jcifs.Config.registerSmbURLHandler();
    }
    /**
     * 读取文本文件内容
     * @param filePathAndName 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回文本文件的内容
     */
    /*
    public String readTxt(String filePathAndName) throws IOException{
        
        StringBuffer str = new StringBuffer("");
        String st = "";
        try{
            SmbFileInputStream in = new SmbFileInputStream(filePathAndName);
            byte buffer[] = new byte[10240] ;
            while((in.read(buffer)) != -1)
               {
                 str.append(buffer+" ");
               }
           

         }catch(Exception e){
          e.printStackTrace();
         }
         st = str.toString();
       
        return st;     
       }
       */

    public String readTxt(String filePathAndName) throws Exception{
        
        SmbFile sf = new SmbFile(filePathAndName);
        int length = sf.getContentLength();
        byte[] fileByteArray = new byte[length];
        int n;
        try{
            SmbFileInputStream in = new SmbFileInputStream(filePathAndName);
            byte buffer[] = new byte[10240] ;
            int start=0;
         while ((n = in.read( buffer )) > 0)
         {
             //System.out.write( buffer, 0, n );
             for(int i=0; i<n; i++)
             {
                 fileByteArray[start+i]=buffer[i];
             }
             start+=n;
         }

         }catch(Exception e){
          e.printStackTrace();
          throw e;
         }      
        return new String(fileByteArray);     
       }
    
    /**
     * 读取文件内容
     * @param filePathAndName 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回文件的内容
     */
    public byte[] readFileByteArray(String filePathAndName) throws Exception{
     SmbFile sf = new SmbFile(filePathAndName);
     int length = sf.getContentLength();
     byte[] str = new byte[length];
     try{
         URL url = new URL(filePathAndName);
         byte[] buf = new byte[10240];
         InputStream in = url.openStream();
         int n;
         int start=0;
         while ((n = in.read( buf )) > 0) {
             //System.out.write( buf, 0, n );
             for(int i=0; i<n; i++)
             {
                 str[start+i]=buf[i];
             }
             start+=n;
         }
         in.close();
        
      }catch(Exception e){
       e.printStackTrace();
       throw e;
      }
    
     return str;     
    }
    
    /**
     * 读取文本文件内容
     * @param filePathAndName 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回文本文件的内容
     */
    public String readFileString(String filePathAndName) throws Exception{
        return new String(this.readFileByteArray(filePathAndName));
    }
    
    /**
     * 返回InputStream,以便在需要读取文件的内容时获取该对象
     * @param filePathAndName 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回InputStream
     */
    public java.io.InputStream getInputStream(String path) throws Exception
    {
        return new SmbFileInputStream(path);
    }
    
    /**
     * 返回OutputStream,以便在需要读取文件的内容时获取该对象
     * @param filePathAndName 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回OutputStream
     */
    public java.io.OutputStream getOutputStream(String path) throws Exception
    {
        path = path.replace("\\", "/");
        SmbFile sf = new SmbFile(path);
        SmbFile parentDir = new SmbFile(sf.getParent());
        if(!parentDir.exists())
        {
            parentDir.mkdirs();
        }
        return new SmbFileOutputStream(path);
    }
    
    
    /**
     * 查询磁盘剩余空间
     * @param path 带有完整绝对路径及其访问口令的的共享文件名
     * e.g: smb://share:share@192.168.1.220/upload/demo.txt
     * @
     * @return 返回磁盘剩余空间
     */
    public long getDiskFreeSpace(String path) throws Exception
    {
        long freespace = 0;
        try {
            SmbFile sf = new SmbFile(path);

            if (sf.exists()) {
                freespace = sf.getDiskFreeSpace();
            }
        } catch (Exception e) {
            //e.printStackTrace();
            message = "查询磁盘剩余空间出错";
            throw new Exception(message);
        } finally {
            return freespace;
        }
    }
    
    /**
     * 新建目录
     *
     * @param folderPath
     *            目录
     * @return 返回目录创建后的路径
     */
    public String createFolder(String folderPath) throws Exception{
        
        try {
            SmbFile myFilePath = new SmbFile(folderPath);
        
            if (!myFilePath.exists()) {
                myFilePath.mkdir();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "创建目录操作出错";
            throw new Exception(message);
        }finally{
        return message;}
    }
    
    /**
     * 多级目录创建
     * @param folderPath
     *
     * @return 返回创建文件后的路径 例如
     */
    public String createFolders(String folderPath) throws Exception {
        String txt = folderPath;
        try {
            SmbFile myFilePath = new SmbFile(txt);
            txt = folderPath;
            if (!myFilePath.exists()) {
                myFilePath.mkdirs();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "创建目录操作出错";
            throw new Exception(message);
        }
        return txt;
    }
    
    /**
     * 新建文件
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param delOldFile 是否删除旧的同名文件
     * @return
     */
    public void createFile(String filePathAndName,boolean delOldFile) throws Exception {
     
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            SmbFile myFilePath = new SmbFile(filePath);
            if(delOldFile)
            {
                myFilePath.createNewFile();
            }else if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
        }
        catch (Exception e) {
            //e.printStackTrace();
            message = "创建文件操作出错";
            throw new Exception(message);
        }
    }
    
    
    /**
     * 新建文件
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param fileContent 文本文件内容
     * @return
     */
    public void createFile(String filePathAndName, String fileContent) throws Exception {
     
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            SmbFile myFilePath = new SmbFile(filePath);
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
            SmbFileOutputStream out=new SmbFileOutputStream(myFilePath);
            

            String strContent = fileContent;
            out.write(fileContent.getBytes());
            out.close();
       
     
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "创建文件操作出错";
            throw new Exception(message);
        }
    }

    /**
     * 文件是否存在
     * @param path 文本文件完整绝对路径及文件名
     * @return boolean是否存在
     */
    public boolean exists(String path) throws Exception
    {
        SmbFile sf = new SmbFile(path);
        return sf.exists();
    }
    
    
    /**
     * 是否是文件夹
     * @param path 文件夹完整绝对路径
     * @return boolean是否是文件夹
     */
    public boolean isDirectory(String path) throws Exception
    {
        boolean isDirectory = false;
        SmbFile sf = new SmbFile(path);
        if(sf.exists())
        {
            isDirectory = sf.isDirectory();
        }
        return isDirectory;
    }
    
    
    /**
     * 是否是文件
     * @param path 文件完整绝对路径及文件名
     * @return boolean是否是文件
     */
    public boolean isFile(String path) throws Exception
    {
        boolean isFile = false;
        SmbFile sf = new SmbFile(path);
        if(sf.exists())
        {
            isFile = sf.isFile();
        }
        return isFile;
    }
    
    /**
     * 获取文件名
     * @param path 文件完整绝对路径及文件名
     * @return 文件名
     */
    public String getName(String path) throws Exception
    {
        String name = "";
        SmbFile sf = new SmbFile(path);
        if(sf.exists())
        {
            name = sf.getName();
        }
        return name;
    }
    
    /**
     * 获取文件名
     * @param path 文件完整绝对路径及文件名
     * @return 文件名
     */
    public String getParent(String path) throws Exception
    {
        String parent = "";
        SmbFile sf = new SmbFile(path);
        if(sf.exists())
        {
            parent = sf.getParent();
        }
        return parent;
    }
    
    /**
     * 有编码方式的文件创建
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param fileContent 文本文件内容
     * @param encoding 编码方式 例如 GBK 或者 UTF-8
     * @return
     */
    public void createFile(String filePathAndName, String fileContent, String encoding) {
     
    }

    /**
     * 删除文件
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @return Boolean 成功删除返回true遭遇异常返回false
     */
    
   
    public boolean delFile(String filePathAndName)throws Exception {
     boolean bea = false;
        try {
            String filePath = filePathAndName;
            SmbFile myDelFile = new SmbFile(filePath);
            if(myDelFile.exists())
            {
                if(myDelFile.isDirectory())
                {
                    if(!(filePathAndName.endsWith("/")))
                    {
                        if(filePathAndName.endsWith("\\"))
                        {
                            filePathAndName = filePathAndName.substring(0, filePathAndName.length());
                        }
                        myDelFile = new SmbFile(filePath+"/");
                    }
                }
              myDelFile.delete();
              bea = true;
            }
            /*
            else{
             bea = false;
             message = (filePathAndName+"删除文件操作出错");
            }
            */
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return bea;
    }
 
    
    /**
     * 删除文件夹
     * @param folderPath 文件夹完整绝对路径
     * @return
     */
    public void delFolder(String folderPath)throws Exception {
        delFile(folderPath);
    }
 
    /**
     * 删除文件或文件夹
     * @param folderPath 文件夹完整绝对路径
     * @return
     */
    public void delete(String folderPath)throws Exception {
        delFile(folderPath);
    }
    
    /**
     * 删除指定文件夹下所有文件
     * @param path 文件夹完整绝对路径
     * @return
     * @return
     */
    public boolean delAllFile(String path)throws Exception {
     boolean bea = false;
    
    try {
         SmbFile file = new SmbFile(path);
        
        if (!file.exists()) {
                return bea;
        }
        
        if (file.isFile()) {
            this.delFile(path);
            return bea;
        }else if(file.isDirectory())
        {
            
            if(!(path.endsWith("/")))
            {
                if(path.endsWith("\\"))
                {
                    path = path.substring(0, path.length());
                }
                file = new SmbFile(path+"/");
            }
            
            SmbFile[] sfs = file.listFiles();
            if(sfs.length>0)
            {
                for(int i=0;i<sfs.length;i++)
                {
                    this.delAllFile(sfs[i].getPath());
                }
            }
            this.delFile(path);
            
        }
        //file.delete();
        //this.delFile(path);
        
    } catch (MalformedURLException e) {
        // TODO 自动生成 catch 块
        e.printStackTrace();
        throw new Exception("删除指定文件夹下所有文件异常");
    }catch (SmbException e) {
        // TODO 自动生成 catch 块
        e.printStackTrace();
    }
        
       
        return bea;
    }

    /**
     * 复制单个文件
     * @param oldPathFile 准备复制的文件源
     * @param newPathFile 拷贝到新绝对路径带文件名
     * @return
     */
    public void copyFile(String oldPathFile, String newPathFile)throws Exception {
        try {
            String newPathFile1 = newPathFile.replace("//", "*");
            //创建目标文件所在文件夹
            if(oldPathFile!=null && newPathFile!=null && !oldPathFile.trim().equals("") && !newPathFile.trim().equals(""))
            {
                if(newPathFile1.length()>1)
                {
                    int index1 = newPathFile.lastIndexOf("/");
                    String newfolderPath = newPathFile.substring(0, index1);
                    
                    int index2 = oldPathFile.lastIndexOf("/");
                    String oldfolderPath = oldPathFile.substring(0, index1);
                    
                    if(!newfolderPath.equals(oldfolderPath))
                    {
                        this.createFolders(newfolderPath);
                    }
                }
                
            }
            int bytesum = 0;
            int byteread = 0;
            SmbFile oldfile = new SmbFile(oldPathFile);
            if (oldfile.exists()) { //文件存在时
                SmbFileInputStream inStream = new SmbFileInputStream(oldPathFile); //读入原文件
                SmbFile fs = new SmbFile(newPathFile);
                SmbFileOutputStream su=new SmbFileOutputStream(fs);
                byte[] buffer = new byte[1444];
                while((byteread =inStream.read(buffer)) != -1){
                    bytesum += byteread; //字节数 文件大小
//                    System.out.println(bytesum);
                    su.write(buffer,0, byteread);
                }
                inStream.close();
                su.close();
            }
        }catch (Exception e) {
            message = ("复制单个文件操作出错");
            throw new Exception(message);
        }
    }
    
    /**
     * 复制单个文件
     * @param srcFilePath         准备复制的文件源
     * @param targerFilePath     拷贝到新绝对路径带文件名
     * @return
     */
    public void copyFile2(String srcFilePath, String targerFilePath) throws Exception{
        try
        {
            //创建目标文件所在文件夹
            if(srcFilePath!=null && targerFilePath!=null && !srcFilePath.trim().equals("") && !targerFilePath.trim().equals(""))
            {
                SmbFile oldsf = new SmbFile(srcFilePath);
                if(oldsf.exists())
                {
                    SmbFile newsf = new SmbFile(targerFilePath);
                    this.createFolders(newsf.getParent());
                    oldsf.copyTo(newsf);
                }
            }
        }catch (Exception e) {
            message = ("复制单个文件操作出错");
            e.printStackTrace();
            throw new Exception(message);
        }
    }
    
     /**
     * 复制整个文件夹的内容
     * @param oldFolderPath 准备拷贝的目录
     * @param newFolderPath 指定绝对路径的新目录
     * @return 被复制的文件夹的文件大小byte
     */
    public long copyFolder(String oldFolderPath, String newFolderPath) throws Exception {
        long bytesize = 0;
        try {
            //new SmbFile(newPath).mkdirs(); //如果文件夹不存在 则建立新文件夹
            this.createFolders(newFolderPath)    ;
            
            if(!newFolderPath.endsWith("/"))
            {
                newFolderPath += "/";
            }
            
            if(!oldFolderPath.endsWith("/"))
            {
                oldFolderPath += "/";
            }
            
            SmbFile a=new SmbFile(oldFolderPath);
            SmbFile[]  file=a.listFiles();
           for (int i = 0; i < file.length; i++)
           {
               SmbFile temp = file[i];
              
              //String canonicalPath = temp.getCanonicalPath();
              //String theoldpath = temp.getPath();
              //int contentLength = temp.getContentLength();
              //URL url = temp.getURL();
              //String Parent = temp.getParent();
              
              if(temp.isFile())
              {                   
                  this.copyFile2(temp.getCanonicalPath(),newFolderPath+temp.getName());
                  bytesize += temp.getContentLength();
              }
              
              if(temp.isDirectory())   //如果是子文件夹
              {
                  copyFolder(temp.getPath(),newFolderPath+temp.getName());
              }  
              
            }  
           return bytesize;
        }catch (Exception e) {
            e.printStackTrace();
            message = "复制整个文件夹内容操作出错";
            throw new Exception(message);
        }
    }
    
    /**
     * 获取指定文件夹的子目录树节点数据
     * @param path 指定的目录
     * @return 子目录树节点数据
     */
    public TreeNode getDirectoryTreeNode(String path) throws Exception {
        try {
            if(!path.endsWith("/"))
            {
                path += "/";
            }
            
            TreeNode treeNode = null;
            SmbFile sf=new SmbFile(path);
            
            if(sf.exists())
            {
                treeNode = new TreeNode();
                //treeNode.setId(path);
                treeNode.setPid(sf.getParent());
                String filename=sf.getName();
                treeNode.setNodeName(filename.substring(0, filename.length()-1));
                
                if(sf.isDirectory())
                {
                    treeNode.setId(path);
                    treeNode.setNodeType("dir");
                    List subTreeNodeList = treeNode.getSubNode();
                    
                    SmbFile[]  file=sf.listFiles();
                    for (int i = 0; i < file.length; i++)
                    {
                      SmbFile temp = file[i];
                      
                      //if(temp.isDirectory())   //如果是子文件夹
                      //{
                          TreeNode subTreeNode = getDirectoryTreeNode(temp.getPath());
                          subTreeNodeList.add(subTreeNode);
                      //}  
                      
                    }
                }else
                {
                    treeNode.setId(path.substring(0, path.length()-1));
                    treeNode.setNodeType("file");
                }
            }
           return treeNode;
        }catch (Exception e) {
            e.printStackTrace();
            message = "获取指定文件夹的子目录树节点数据出错";
            throw new Exception(message);
        }
    }


    /**
     * 移动文件
     * @param oldPath
     * @param newPath
     * @return
     */
    public void moveFile(String oldPath, String newPath)throws Exception {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }
    
    /**
     * 移动目录
     * @param oldPath
     * @param newPath
     * @return
     * @throws Exception
     */
    public void moveFolder(String oldPath, String newPath) throws Exception {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }
    public String getMessage(){
        return this.message;
    }

    /**
     * 获取指定文件的大小
     * @param path 指定的文件
     * @return 文件大小
     */
    public long getFileSize(String path) throws Exception {
        // TODO 自动生成方法存根
        Long fileSize = 0l;
        try {
            SmbFile sf = new SmbFile(path);
            if(sf.exists())
            {
                fileSize = new Long(sf.getContentLength());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return fileSize;
    }
    
    
    /**
     * 文件或目录重命名
     * @param srcPath 源文件完整绝对路径
     * @param targetPath 新的文件完整绝对路径
     * @return Boolean 成功删除返回true遭遇异常返回false
     */
    
   
    public boolean rename(String srcPath,String targetPath)throws Exception {
     boolean bea = false;
        try {
            SmbFile sfsrc = new SmbFile(srcPath);
            SmbFile sftarget = new SmbFile(targetPath);
            if(sfsrc.exists())
            {
                sfsrc.renameTo(sftarget);
                bea = true;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return bea;
    }
    
    
    public static void main(String[] args) {
        // TODO 自动生成方法存根
            
        try
         {
           SmbFileOperate sfo= new SmbFileOperate();
/*
           sfo.createFile(GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/1/remote20.txt", "abc中文");
           //单个文件复制ok
           //sfo.copyFile(GlobalsShare.SMBFILESERVERIP+"/doclib/1234567p/remote.txt",GlobalsShare.SMBFILESERVERIP+"/doclib/upfile2/test2/remote.txt");
           sfo.copyFile2(GlobalsShare.SMBFILESERVERIP+"/doclib/1234567p/remote.txt",GlobalsShare.SMBFILESERVERIP+"/doclib/upfile3/test2/remote3.txt");
//         sfo.copyFile("smb://test:1@192.168.1.220/upfile/test/remote.txt","smb://test:1@192.168.1.220/upfile/test1/remote.txt");
            
        
           sfo.createFolder(GlobalsShare.SMBFILESERVERIP+"/upload/innermail/attachment/1234567p")    ;
           //sfo.createFolder("smb://smbtest:smbtest@192.168.1.253/doclib/1234567p/1/2")    ;
           
           //创建多级文件夹ok
           sfo.createFolders(GlobalsShare.SMBFILESERVERIP+"/doclib/1234567p")    ;
           
           //目录拷贝ok
           int allsize = sfo.copyFolder(GlobalsShare.SMBFILESERVERIP+"/doclib/1234567p/",GlobalsShare.SMBFILESERVERIP+"/doclib/ta5/1/");
           System.out.println("size=" + allsize + " byte");
//         sfo.copyFolder("smb://test:1@192.168.1.220/upfile","smb://test:1@192.168.1.220/upfile/test1/22");
           
           //删除文件和目录(如果文件夹下有文件和子目录,也会全部删除)
           sfo.delFile(GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/");
           
           //目录移动
           sfo.moveFolder(GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/", GlobalsShare.SMBFILESERVERIP+"/doclib/ta3/");
           
           //文件移动
           sfo.moveFile(GlobalsShare.SMBFILESERVERIP+"/doclib/ta3/1/remote.txt", GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/1/remote2.txt");
           
           //文件读取
           String content = sfo.readTxt(GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/1/remote2.txt");
           //System.out.println(content);
           
//         文件读取
           byte[] content2 = sfo.readFileByteArray(GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/1/remote2.txt");
           //System.out.println(new String(content2));
           
           String fileString = sfo.readFileString(GlobalsShare.SMBFILESERVERIP+"/doclib/ta2/1/remote2.txt");
           //System.out.println(fileString);
*/
          // System.out.println(sfo.getDiskFreeSpace("smb://smbtest:smbtest@192.168.1.253/doclib/档案2"));
          //File file = new File("D:/doclib/档案2/档案21/1230版南电计划考核BUG.doc");
          //System.out.println(file.length()/1000000.0);
           
          //String path = "smb://smbtest:smbtest@192.168.1.253/doclib/";
          //TreeNode tnode = sfo.getDirectoryTreeNode(path);
          //System.out.print("****");
          
          //String content = sfo.readTxt("smb://smbtest:smbtest@192.168.1.253/doclibbak/aaa\\abc.txt");
           //System.out.println(content);
          
           //sfo.delFile("smb://smbtest:smbtest@192.168.1.253/doclib/ta2/2");
           //sfo.delAllFile("smb://smbtest:smbtest@192.168.1.253/doclib/ta2/2");
           
           //sfo.rename("smb://smbtest:smbtest@192.168.1.253/doclib/ta5/4", "smb://smbtest:smbtest@192.168.1.253/doclib/ta5/1/1");
           
           //sfo.getOutputStream("smb://smbtest:smbtest@192.168.1.253/doclibbak/sunhua/档案2\\档案21/20081006南热电物料系统改进设计2.doc ");
           
           sfo.copyFolder("smb://smbtest:smbtest@192.168.1.253/doclib/ta1", "smb://smbtest:smbtest@192.168.1.253/doclib/ta100");
           
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            System.out.print("see u at last");
        }
    }
    private static int getContentLength() {
        // TODO Auto-generated method stub
        return 0;
    }

}

//本地磁盘操作类
public class LocalDiskXfile implements XfileInterface {

    public void copyFile(String srcFilePath, String targerFilePath)
            throws Exception {
        // TODO 文件复制
        FileInputStream in=new FileInputStream(srcFilePath);
        File file=new File(targerFilePath);
        if(!file.exists())
        {
            file.createNewFile();
        }
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
         while((c=in.read(buffer))!=-1){
            for(int i=0;i<c;i++)
                out.write(buffer[i]);        
        }
        in.close();
        out.close();
    }

    public long copyFolder(String oldFolderPath, String newFolderPath) throws Exception {
        // TODO 自动生成方法存根
        long ret = copyFolder(oldFolderPath, newFolderPath,false);
        return ret;
    }

    /**
     * 复制目录
     *
     * @param oldPath
     *            准备拷贝的目录
     * @param newPath
     *            指定绝对路径的新目录
     * @param isCopyFolder
     *            是否复制根目录 true 为复制根目录 false 为不复制根目录,只复制根目录下的所有文件以及文件夹
     * @return 成功复制返回>=0的long值 遭遇异常返回-1
     */
    public static long copyFolder(String oldPath, String newPath,boolean isCopyFolder) {
        //文件大小
        long bytesize = 0;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {

            mkdirs2(newPath);
            oldPath = oldPath.replace(File.separator, "/");
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            String oldForder;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith("/")) {
                    oldPath = oldPath.substring(0, oldPath.length() - 1);
                }
                oldForder = oldPath.substring(oldPath.lastIndexOf("/") + 1);
                temp = new File(oldPath + File.separator + files[i]);
                Long thesize = 0L;
                if (temp.isFile()) {
                    
                    thesize = temp.length();
                    
                    inputStream = new FileInputStream(temp);
                    if (isCopyFolder) {
                        mkdirs2(newPath + "/" + oldForder);
                        outputStream = new FileOutputStream(newPath + "/" + oldForder + "/" + (temp.getName()).toString());
                    } else {
                        outputStream = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
                    }

                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = inputStream.read(b)) != -1) {
                        outputStream.write(b, 0, len);
                        outputStream.flush();
                    }
                } else if (temp.isDirectory()) {// 如果是子文件夹
                    
                    if (isCopyFolder) {
                        thesize = copyFolder(oldPath + "/" + files[i], newPath + "/" + oldForder + "/" + files[i], isCopyFolder);
                    } else {
                        thesize = copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i], isCopyFolder);
                    }
                    
                }
                
//                计算文件大小
                if(thesize != -1)
                {
                    bytesize += thesize;
                    return bytesize;
                }else
                {
                    return -1L;
                }
                
            }
        } catch (Exception e) {
            bytesize = -1;
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (Exception ex) {
                bytesize = -1;
            }
        }
        return bytesize;
    }
    
    public void createNewFile(String path, boolean delOldFile) throws Exception {
        // TODO 自动生成方法存根
        
        try {
            File file=new File(path);
            
            if(delOldFile)
            {
                file.createNewFile();
            }else if (!file.exists())
            {
                file.createNewFile();
            }
        }
        catch (Exception e) {
            //e.printStackTrace();
            String message = "创建文件操作出错";
            throw new Exception(message);
        }
    }

    public void createNewFile(String path, String fileContent) throws Exception {
        // TODO 自动生成方法存根
        try
        {
            FileWriter fileWriter = new FileWriter(path);
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(fileContent);
            bw.flush();
            bw.close();
        }
        catch (Exception e) {
            //e.printStackTrace();
            String message = "创建文件操作出错";
            throw new Exception(message);
        }
    }

    //删除文件或文件夹
    public void delete(String path) throws Exception {
        // TODO 自动生成方法存根
            File file = new File(path);
            if (!file.exists()) {
                return;
            }
            if (!file.isDirectory()) {
                file.delete();
                return;
            }
            String[] tempList = file.list();
            File temp = null;
            for (int i = 0; i < tempList.length; i++) {
                if (path.endsWith(File.separator)) {
                    temp = new File(path + tempList[i]);
                }else{
                    temp = new File(path + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
                if (temp.isDirectory()) {
                    delete(path+"/"+ tempList[i]);//先删除文件夹里面的文件
                    deleteFile(path+"/"+ tempList[i]);//再删除空文件夹
                }
            }
            file.delete();
    }

    //删除一个文件
    public static boolean deleteFile(String filePathAndName) {
        boolean ret = false;
        try {
            File myDelFile = new File(filePathAndName);
            if (myDelFile.isFile() && myDelFile.exists()) {
                myDelFile.delete();

                ret = true;
            } else {
                ret = false;
            }

        } catch (Exception e) {
            ret = false;
        }
        return ret;
    }
    
    public boolean exists(String path) throws Exception {
        // TODO 文件是否存在
        try {
            File file=new File(path);
            return file.exists();
        }
        catch (Exception e) {
            //e.printStackTrace();
            String message = "创建文件操作出错";
            throw new Exception(message);
        }
    }

    public TreeNode getDirectoryTreeNode(String path) throws Exception {
        // TODO 自动生成方法存根
        try {
            //if(!path.endsWith("/"))
            //{
            //    path += "/";
            //}
            TreeNode treeNode = null;
            File sf=new File(path);
            
            if(sf.exists())
            {
                treeNode = new TreeNode();
                treeNode.setId(path);
                treeNode.setPid(sf.getParent());
                String filename=sf.getName();
                if(filename.endsWith("/"))
                {
                    filename = filename.substring(0, filename.length()-1);
                }
                treeNode.setNodeName(filename);
                
                if(sf.isDirectory())
                {
                    treeNode.setNodeType("dir");
                    List subTreeNodeList = treeNode.getSubNode();
                    
                    File[]  file=sf.listFiles();
                   for (int i = 0; i < file.length; i++)
                   {
                      File temp = file[i];
                      
                      //if(temp.isDirectory())   //如果是子文件夹
                      //{
                          TreeNode subTreeNode = getDirectoryTreeNode(temp.getPath());
                          subTreeNodeList.add(subTreeNode);
                      //}  
                      
                    }
                }else
                {
                    treeNode.setNodeType("file");
                }
            }
           return treeNode;
        }catch (Exception e) {
            e.printStackTrace();
            String message = "获取指定文件夹的子目录树节点数据出错";
            throw new Exception(message);
        }
    }

    public long getDiskFreeSpace(String path) throws Exception {
        // TODO 自动生成方法存根
        long freespace = 0;
        try {
            File sf = new File(path);

            //if (sf.exists()) {
                freespace = DiskSpace.getFreeDiskSpace(path);
            //}
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "查询磁盘剩余空间出错";
            throw new Exception(message);
        } finally {
            return freespace;
        }
    }

    public long getFileSize(String path) throws Exception {
        // TODO 自动生成方法存根
        long filesize = 0;
        try {
            File sf = new File(path);

            if (sf.exists()) {
                filesize = sf.length();
            }
            return filesize;
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "查询文件大小出错";
            throw new Exception(message);
        }
    }

    public InputStream getInputStream(String path) throws Exception {
        // TODO 自动生成方法存根
        try {
            return new FileInputStream(path);
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "获取文件InputStream出错";
            throw new Exception(message);
        }
    }

    public String getName(String path) throws Exception {
        // TODO 自动生成方法存根
        String filename = "";
        try {
            File sf = new File(path);

            if (sf.exists()) {
                filename = sf.getName();
            }
            return filename;
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "查询文件大小出错";
            throw new Exception(message);
        }
    }

    public OutputStream getOutputStream(String path) throws Exception {
        // TODO 自动生成方法存根
        try {
            return new FileOutputStream(path);
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "获取文件OutputStream出错";
            throw new Exception(message);
        }
    }

    public String getParent(String path) throws Exception {
        // TODO 自动生成方法存根
        String parentName = "";
        try {
            File sf = new File(path);

            if (sf.exists()) {
                parentName = sf.getParent();
            }
            return  parentName;
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "查询文件父目录出错";
            throw new Exception(message);
        }
    }

    public boolean isDirectory(String path) throws Exception {
        // TODO 自动生成方法存根
        boolean isDir = false;
        try {
            File sf = new File(path);

            if (sf.exists() && sf.isDirectory()) {
                isDir = true;
            }
            return isDir;
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "查询文件isDirectory出错";
            throw new Exception(message);
        }
    }

    public boolean isFile(String path) throws Exception {
        // TODO 自动生成方法存根
        boolean isfile = false;
        try {
            File sf = new File(path);

            if (sf.exists() && sf.isFile()) {
                isfile = true;
            }
            return isfile;
        } catch (Exception e) {
            //e.printStackTrace();
            String message = "查询文件isDirectory出错";
            throw new Exception(message);
        }
    }

    public void mkdir(String path) throws Exception {
        // TODO 自动生成方法存根
        File sf = new File(path);
        sf.mkdir();
    }

    public void mkdirs(String path) throws Exception {
        // TODO 自动生成方法存根
        File sf = new File(path);
        sf.mkdirs();
    }
    
    public static void mkdirs2(String path) throws Exception {
        // TODO 自动生成方法存根
        File sf = new File(path);
        sf.mkdirs();
    }

    public void moveFile(String srcFilePath, String targerFilePath)
            throws Exception {
        // TODO 自动生成方法存根
        File oldfile = new File(srcFilePath);
        File newfile = new File(targerFilePath);
        if(oldfile.exists())
        {
            File newfileParent = newfile.getParentFile();
            if(!newfileParent.exists())
            {
                newfileParent.mkdirs();
            }
            oldfile.renameTo(newfile);
        }
    }

    public void moveFolder(String oldFolderPath, String newFolderPath)
            throws Exception {
        // TODO 自动生成方法存根
        File oldfile = new File(oldFolderPath);
        File newfile = new File(newFolderPath);
        if(oldfile.exists())
        {
            File newfileParent = newfile.getParentFile();
            if(!newfileParent.exists())
            {
                newfileParent.mkdirs();
            }
            oldfile.renameTo(newfile);
        }
    }

    public boolean rename(String srcFilePath, String targerFilePath) throws Exception {
        // TODO 自动生成方法存根
        File oldfile = new File(srcFilePath);
        File newfile = new File(targerFilePath);
        if(oldfile.exists())
        {
            File newfileParent = newfile.getParentFile();
            if(!newfileParent.exists())
            {
                newfileParent.mkdirs();
            }
            oldfile.renameTo(newfile);
        }
        return true;
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO 自动生成方法存根
        String srcFilePath = "D:\\test2\\log33.txt";
        //String targerFilePath = "D:\\test2\\dir1\\log33.txt";
        String targerFilePath = "E:\\test2\\dir1\\log33.txt";
        LocalDiskXfile ldxf = new LocalDiskXfile();
//        ldxf.moveFolder(srcFilePath, targerFilePath);
        
        //copyFolder("D:\\test2", "E:\\test2\\dir1\\",true);
        //copyFolder("D:\\test2", "E:\\test2\\dir1\\",false);
        ldxf.delete("E:\\test2\\dir1\\test2");
    }

}

public class DiskSpace {
 public static final String CRLF = System.getProperty("line.separator");  
  public static final int OS_Unknown  = 0;  
  public static final int OS_WinNT  = 1;  
  public static final int OS_Win9x  = 2;  
  public static final int OS_Linux  = 3;  
  public static final int OS_Unix  = 4;  
    
  private static Log   _log = LogFactory.getLog(DiskSpace.class);  
  private static String  _os = System.getProperty("os.name");  
  protected static String os_exec(String[] cmds) {  
   int   ret = 0;  
   Process  porc = null;
   InputStream perr = null, pin = null;   
   StringBuffer sb = new StringBuffer();  
   String  line = null;  
   BufferedReader br = null;  
   try {  
   // for(int i=0; i porc = Runtime.getRuntime().exec(cmds);//执行编译操作
    porc = Runtime.getRuntime().exec(cmds, null, null);
    perr = porc.getErrorStream();  
    pin  = porc.getInputStream();  
    // 获取屏幕输出显示
    // while((c=pin.read())!=-1) sb.append((char) c);
    br = new BufferedReader(new InputStreamReader(pin));  
    while((line=br.readLine())!=null) {  
    // System.out.println("exec()O: "+line);
     sb.append(line).append(CRLF);  
    }  
    // 获取错误输出显示
    br = new BufferedReader(new InputStreamReader(perr));  
    while((line=br.readLine())!=null) {  
     System.err.println("exec()E: "+line);  
    }  
    porc.waitFor();   // 等待编译完成
    ret = porc.exitValue(); // 检查javac错误代码
    if (ret!=0) {  
     _log.warn("porc.exitValue() = "+ret);  
    }     
   }catch(Exception e) {  
    _log.warn("exec() "+e, e);  
   }finally {  
    porc.destroy();  
   }  
   return sb.toString();  
  }  
    
  protected static int os_type() {  
         // _log.debug("os.name = "+os); //Windows XP
         String os = _os.toUpperCase();  
         
         //操作系统环境变量
         String systemenv_os = System.getenv("OS")==null?"":System.getenv("OS");
         if(systemenv_os.toUpperCase().equals("WINDOWS_NT")) return OS_WinNT;
         
         if (os.startsWith("WINDOWS")) {  
          if (os.endsWith("NT") || os.endsWith("2000") || os.endsWith("XP"))  
           return OS_WinNT;  
          else return OS_Win9x;  
         }else if (os.indexOf("LINUX")>0) return OS_Linux;  
         else if (os.indexOf("UX")>0)   return OS_Unix;  
         else           return OS_Unknown;  
   }  
  protected static long os_freesize(String dirName) {  
   String[] cmds = null;  
   long freeSize = -1;  
   int osType = os_type();  
   switch(osType) {  
   case OS_WinNT:  
       dirName = dirName.replace("/", "\\");
       cmds = new String[]{"cmd.exe", "/c", "dir", dirName};  
       freeSize = os_freesize_win(os_exec(cmds));  
       break;  
   case OS_Win9x:
       dirName = dirName.replace("/", "\\");
       cmds = new String[]{"command.exe", "/c", "dir", dirName};  
       freeSize = os_freesize_win(os_exec(cmds));  
       break;  
   case OS_Linux:  
   case OS_Unix:  
       cmds = new String[]{"df", dirName};  
       freeSize = os_freesize_unix(os_exec(cmds));  
       break;  
           default:  
   }  
   return freeSize;  
  }
 
 
  protected static String[] os_split(String s)
  {  
 // _log.debug("os_split() "+s);
   String[] ss = s.split(" "); // 空格分隔;
   List ssl = new ArrayList(16);
   for(int i=0; i<ss.length; i++)
   {
       if (ss[i]==null)  continue;  
       ss[i] = ss[i].trim();  
       if (ss[i].length()==0) continue;  
       ssl.add(ss[i]);  
 // _log.debug("os_split() "+ss[i]);
   }  
   String[] ss2 = new String[ssl.size()];  
   ssl.toArray(ss2);  
   return ss2;  
  }


  private static long os_freesize_unix(String s) {  
   String lastLine = os_lastline(s); // 获取最后一航;
   if (lastLine == null) {  
          _log.warn("(lastLine == null)"); return -1;  
         }else lastLine = lastLine.trim();  
   // 格式:/dev/sda1 101086 12485 83382 14% /boot
   // lastLine = lastLine.replace('\t', ' ');
   String[] items = os_split(lastLine);  
//   _log.debug("os_freesize_unix() 目录:\t"+items[0]);  
//   _log.debug("os_freesize_unix() 总共:\t"+items[1]);  
//   _log.debug("os_freesize_unix() 已用:\t"+items[2]);  
//   _log.debug("os_freesize_unix() 可用:\t"+items[3]);  
//   _log.debug("os_freesize_unix() 可用%:\t"+items[4]);  
//   _log.debug("os_freesize_unix() 挂接:\t"+items[5]);  
   if(items[3]==null) {  
    _log.warn("(ss[3]==null)");   return -1;  
   }  
   return Long.parseLong(items[3])*1024; // 按字节算
  }  
  private static long os_freesize_win(String s) {  
   String lastLine = os_lastline(s); // 获取最后一航;
   if (lastLine == null) {  
          _log.warn("(lastLine == null)");  
             return -1;  
         }else lastLine = lastLine.trim().replaceAll(",", "");  
   // 分析
   String items[] = os_split(lastLine); // 15 个目录 1,649,696,768 可用字节
   if (items.length<4) { _log.warn("DIR result error: "+lastLine); return -1;}  
   if (items[2]==null) { _log.warn("DIR result error: "+lastLine); return -1;}  
         long bytes = Long.parseLong(items[2]); // 1,649,696,768
         return bytes;  
  }  
  protected static String os_lastline(String s) {  
   // 获取多行输出的最后一行;
   BufferedReader br = new BufferedReader(new StringReader(s));  
   String line = null, lastLine=null;  
   try {  
    while((line=br.readLine())!=null) lastLine = line;  
   }catch(Exception e) {  
    _log.warn("parseFreeSpace4Win() "+e);  
   }  
   // _log.debug("os_lastline() = "+lastLine);
   return lastLine;    
  }  
 // private static String os_exec_df_mock() { //模拟df返回数据
 // StringBuffer sb = new StringBuffer();
 // sb.append("Filesystem 1K-块 已用 可用 已用% 挂载点");
 // sb.append(CRLF);
 // sb.append("/dev/sda1 101086 12485 83382 14% /boot");
 // sb.append(CRLF);
 // return sb.toString();
 // }
     public static long getFreeDiskSpace(String dirName) {  
         // return os_freesize_unix(os_exec_df_mock()); //测试Linux
   return os_freesize(dirName);// 自动识别操作系统,自动处理
     }  
     public static void main(String[] args) throws IOException {  
      //UtilLog.configureClassPath("resources/log4j.properties", false);  
      args = new String[3]; int x=0;  
      args[x++] = "C:";     args[x++] = "D:"; args[x++] = "E:";  
         if (args.length == 0){  
             for (char c = 'A'; c <= 'Z'; c++) {  
                 String dirName = c + ":\\";  // C:\ C:
                 //_log.info(dirName + " " + getFreeDiskSpace(dirName));  
                 System.out.println(dirName + " " + getFreeDiskSpace(dirName));
             }  
         }else{  
             for (int i = 0; i < args.length; i++) {  
              //_log.info(args[i] + " 剩余空间(B):" + getFreeDiskSpace(args[i]));
              System.out.println(args[i] + " 剩余空间(B):" + getFreeDiskSpace(args[i]));
             }  
         }
         String path="D:/doc-zzh/downdoc/java";
         //path = path.replace("/", "\\");
         System.out.println("D:\\doc-zzh\\downdoc\\java 剩余空间(B):" + getFreeDiskSpace(path));
     }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值