IO操作(已封装)--java

和大家见面了,本人言语突然很少,开门见山吧

package  cn.vetech.framework.util;

import  java.io.BufferedReader;
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.FileOutputStream;
import  java.io.IOException;
import  java.io.InputStream;
import  java.io.InputStreamReader;
import  java.io.OutputStream;
import  java.io.PrintWriter;

import  org.apache.struts.upload.FormFile;

import  cn.vetech.framework.source.Constants;

/**
 * 用户文件的 读 写 目录的创建等
 * 
 * 
@author  zl
 * 
 
*/
public   class  FileOperate {
    
private  String message;

    
private  String FILESPARA  =   " / " ;

    
private  String spath  =  Constants.APPPRTH;

    
public  FileOperate() {
    }

    
/**
     * 强制用UTF-8 编码读 整个系统编码采用utf-8
     * 
     * 
@param  filePathAndName
     * 
@return
     
*/
    
public  String readTxt(String filePathAndName) {
        
return  readTxt(filePathAndName,  " UTF-8 " );
    }

    
/**
     * 读取文本文件内容
     * 
     
*/
    
public  String readTxt(String filePathAndName, String encoding) {
        encoding 
=  encoding.trim();
        StringBuffer str 
=   new  StringBuffer( "" );
        String st 
=   "" ;
        
try  {
            FileInputStream fs 
=   new  FileInputStream(filePathAndName);
            InputStreamReader isr;
            
if  (encoding.equals( "" )) {
                isr 
=   new  InputStreamReader(fs);
            } 
else  {
                isr 
=   new  InputStreamReader(fs, encoding);
            }
            BufferedReader br 
=   new  BufferedReader(isr);
            
try  {
                String data 
=   "" ;
                
while  ((data  =  br.readLine())  !=   null ) {
                    str.append(data 
+   "   " );
                }
            } 
catch  (Exception e) {
                str.append(e.toString());
            }
            st 
=  str.toString();
        } 
catch  (IOException es) {
            st 
=   "" ;
        }
        
return  st;
    }

    
/**
     * 强制用UTF-8 编码保存 避免因为操作系统不同而编码不同。
     * 
     * 
@param  path
     * 
@param  filename
     * 
@param  fileContent
     
*/
    
public   void  writeTxt(String path, String filename, String fileContent) {
        writeTxt(path, filename, fileContent, 
" UTF-8 " );

    }

    
/**
     * 有编码方式的文件创建
     
*/
    
public   void  writeTxt(String path, String filename, String fileContent, String encoding) {

        
try  {
            File file 
=   new  File(path);
            
if  ( ! file.exists()) {
                file.mkdirs();
            }
            file 
=   new  File(path  +  FILESPARA  +  filename);
            PrintWriter pwrite 
=   null ;
            
if  (encoding  !=   null   &&   ! "" .equals(encoding)) {
                pwrite 
=   new  PrintWriter(file, encoding);
            } 
else  {
                pwrite 
=   new  PrintWriter(file);
            }
            pwrite.println(fileContent);
            pwrite.close();
        } 
catch  (Exception e) {
            e.printStackTrace();
        }
    }

    
/**
     * 拷贝目录树 把一个目录下的所有东西包括子目录 同时拷贝到 另外一个目录
     * 
     * 
@param  sourceDir
     * 
@param  targetDir
     * 
@throws  Exception
     
*/
    
public   void  copyDir(String sourceDir, String targetDir)  throws  Exception {
        String url1 
=  sourceDir;
        String url2 
=  targetDir;
        
if  ( ! ( new  File(url2)).exists()) {
            (
new  File(url2)).mkdirs();
        }
        File[] file 
=  ( new  File(url1)).listFiles();
        
for  ( int  i  =   0 ; i  <  file.length; i ++ ) {
            
if  (file[i].isFile()) {
                file[i].toString();
                FileInputStream input 
=   new  FileInputStream(file[i]);
                FileOutputStream output 
=   new  FileOutputStream(url2  +  System.getProperty( " file.separator " )
                        
+  (file[i].getName()).toString());
                
byte [] b  =   new   byte [ 1024   *   5 ];
                
int  len;
                
while  ((len  =  input.read(b))  !=   - 1 ) {
                    output.write(b, 
0 , len);
                }
                output.flush();
                output.close();
                input.close();
            } 
else   if  (file[i].isDirectory()) {
                String url_2_dir 
=  url2  +  System.getProperty( " file.separator " +  file[i].getName();
                copyDir(file[i].getPath(), url_2_dir);
            }
        }
    }

    
/**
     * 新建目录
     * 
     * 
@param  folderPath
     *            目录
     * 
@return  返回目录创建后的路径
     
*/
    
public  String createFolder(String folderPath) {
        String txt 
=  folderPath;
        
try  {
            java.io.File myFilePath 
=   new  java.io.File(txt);
            txt 
=  folderPath;
            
if  ( ! myFilePath.exists()) {
                myFilePath.mkdirs();
            }
        } 
catch  (Exception e) {
            message 
=   " 创建目录操作出错 " ;
        }
        
return  txt;
    }

    
/**
     * 删除文件
     * 
     * 
@param  filePathAndName
     *            文本文件完整绝对路径及文件名
     * 
@return  Boolean 成功删除返回true遭遇异常返回false
     
*/
    
public   boolean  delFile(String filePathAndName) {
        
boolean  bea  =   false ;
        
try  {
            String filePath 
=  filePathAndName;
            File myDelFile 
=   new  File(filePath);
            
if  (myDelFile.exists()) {
                myDelFile.delete();
                bea 
=   true ;
            } 
else  {
                bea 
=   false ;
                message 
=  (filePathAndName  +   " <br>删除文件操作出错 " );
            }
        } 
catch  (Exception e) {
            message 
=  e.toString();
        }
        
return  bea;
    }

    
/**
     * 删除文件夹
     * 
     * 
@param  folderPath
     *            文件夹完整绝对路径
     * 
@return
     
*/
    
public   void  delFolder(String folderPath) {
        
try  {
            delAllFile(folderPath); 
//  删除完里面所有内容
            String filePath  =  folderPath;
            filePath 
=  filePath.toString();
            java.io.File myFilePath 
=   new  java.io.File(filePath);
            myFilePath.delete(); 
//  删除空文件夹
        }  catch  (Exception e) {
            message 
=  ( " 删除文件夹操作出错 " );
        }
    }

    
/**
     * 删除指定文件夹下所有文件
     * 
     * 
@param  path
     *            文件夹完整绝对路径
     * 
@return
     * 
@return
     
*/
    
public   boolean  delAllFile(String path) {
        
boolean  bea  =   false ;
        File file 
=   new  File(path);
        
if  ( ! file.exists()) {
            
return  bea;
        }
        
if  ( ! file.isDirectory()) {
            
return  bea;
        }
        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()) {
                delAllFile(path 
+   " / "   +  tempList[i]); //  先删除文件夹里面的文件
                delFolder(path  +   " / "   +  tempList[i]); //  再删除空文件夹
                bea  =   true ;
            }
        }
        
return  bea;
    }

    
/**
     * 复制单个文件
     * 
     * 
@param  oldPathFile
     *            准备复制的文件源
     * 
@param  newPathFile
     *            拷贝到新绝对路径带文件名
     * 
@return
     
*/
    
public   void  copyFile(String oldPathFile, String newPathFile) {
        
try  {
            
int  bytesum  =   0 ;
            
int  byteread  =   0 ;
            File oldfile 
=   new  File(oldPathFile);
            
if  (oldfile.exists()) {  //  文件存在时
                InputStream inStream  =   new  FileInputStream(oldPathFile);  //  读入原文件
                FileOutputStream fs  =   new  FileOutputStream(newPathFile);
                
byte [] buffer  =   new   byte [ 1444 ];
                
while  ((byteread  =  inStream.read(buffer))  !=   - 1 ) {
                    bytesum 
+=  byteread;  //  字节数 文件大小
                    
//   // System.out.println(bytesum);
                    fs.write(buffer,  0 , byteread);
                }
                inStream.close();
            }
        } 
catch  (Exception e) {
            message 
=  ( " 复制单个文件操作出错 " );
        }
    }

    
/**
     * 移动文件
     * 
     * 
@param  oldPath
     * 
@param  newPath
     * 
@return
     
*/
    
public   void  moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    
/**
     * 移动目录
     * 
     * 
@param  oldPath
     * 
@param  newPath
     * 
@return
     * 
@throws  Exception
     
*/
    
public   void  moveFolder(String sourceDir, String targetDir)  throws  Exception {
        copyDir(sourceDir, targetDir);
        delFolder(sourceDir);
    }

    
public  String getMessage() {
        
return   this .message;
    }

    
/**
     * ybfjm@163.com 扩充
     
*/
    
/**  以下是保存文件,读取文件需要用到的方法*  */
    
public  String getStringFilePath(String id) {
        String strPath 
=   "" ;
        
//  生成一个目录,生成年度、月份目录
        String sfolder_year  =  id.substring( 0 4 );
        String sfolder_month 
=  id.substring( 4 6 );
        strPath 
=  spath  +   " /updownFiles/ "   +  sfolder_year  +  FILESPARA  +  sfolder_month  +  FILESPARA;
        
return  strPath;
    }

    
public  String getFileByPathId(String pathFile) {
        File myFile 
=   new  File(pathFile);
        
if  (myFile.exists())
            
return   new  FileOperate().readTxt(pathFile);
        
else
            
return   "" ;
    }

    
public   void  saveFileByPathId(String path, String id, String nr) {
        
new  FileOperate().writeTxt(path, id  +   " .txt " , nr);
    }

    
public   void  delFileByPathId(String pathFile) {
        File myFile 
=   new  File(pathFile);
        
if  (myFile.exists())
            
new  FileOperate().delFile(pathFile);
    }

    
/*
     * 用于上传文件保存 如果saveFileName 为空那么将以FormFile 文件名保存 不包括扩展名,扩展名自动引用 返回保存的文件名
     * 如果返回为空表示有错误
     
*/
    
public  String uploadFileSave(FormFile file, String savePath, String saveFileName) {
        String slowdamc 
=   "" ;
        
if  (file  ==   null ) {
            
return   "" ;
        }
        
try  {
            InputStream stream 
=  file.getInputStream(); //  把文件读入
        
//     ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String fileName  =  file.getFileName().toLowerCase();
            
if  (fileName  ==   null   ||   "" .equals(fileName)) {
                
return   "" ;
            }
            
if  (saveFileName  ==   null   ||   "" .equals(saveFileName)) {
                slowdamc 
=  fileName;
            } 
else  {
                
if  (fileName.indexOf( " . " !=   - 1 ) {
                    slowdamc 
=  saveFileName  +   " . "   +  getFileExt(fileName);
                } 
else  {
                    slowdamc 
=  saveFileName;
                }

            }
    
//         long isize = file.getFileSize();
            
//  如果目录不存在就创建目录
            createFolder(savePath);
            OutputStream bos 
=   new  FileOutputStream(savePath  +  Constants.FILESPARA  +  slowdamc); //  建立一个上传文件的输出流
             int  bytesRead  =   0 ;
            
byte [] buffer  =   new   byte [ 8192 ];
            
while  ((bytesRead  =  stream.read(buffer,  0 8192 ))  !=   - 1 ) {
                bos.write(buffer, 
0 , bytesRead); //  将文件写入服务器
            }
            bos.close();
            stream.close();
        } 
catch  (Exception e) {
            System.err.print(e);
            
return   "" ;
        }
        
return  slowdamc;
    }

    
/**
     * 获取文件扩展名 ybf 2006/08/02
     * 
     * 
@param  filename
     * 
@return
     
*/
    
public  String getFileExt(String filename) {
        
if  ((filename  !=   null &&  (filename.length()  >   0 )) {
            
int  i  =  filename.lastIndexOf( ' . ' );

            
if  ((i  >   0 &&  (i  <  (filename.length()  -   1 ))) {
                
return  filename.substring(i  +   1 );
            }
        }
        
return   "" ;
    }

}

工具类

package  cn.vetech.framework.source;

/**
 * 静态变量资源定义类
 * 
 * 
@author  vesoft
 * 
 
*/

public   final   class  Constants {
    
//  发布绝对路径
     public   static  String APPPRTH  =   " D:/webapps/ask123.net " ;
    
//  文件分割符
     public   static  String FILESPARA  =   " / " ;

    
//  允许上传的图片扩展名
     public   static  String picExt  =   " JPEG|JPG|BMP|GIF|TIF|PNG|ICO| " ;

    
//  允许上传的文件扩展名
     public   static  String fileAllowExt  =   " DOC|DOT|XLS|XLT|POT|PPT|PPS|PDF|RAR|ZIP|VSD|JPEG|JPG|BMP|GIF|TIF|PNG|ICO|AVI|MIDI|MOV|WMA|RM|MP3|SWF|TXT|FLV| " ;

    
//  上传文件大小KB等级 ,默认为 等级 5(40M). 等级为0不允许上传.

    
public   static   int [] fileSize  =  {  0 1024 1024   *   2 1024   *   4 1024   *   5 1024   *   40  };

    
//  对于图片文件,为了加快浏览速度特许要求,大小不能超过300K.
     public   static   int  picFileSize  =   300 ;
}

 

爽吧?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值