java中io操作文件跟文件内容实例

复制整个文件,或者文本文件中的内容相关操作可参考下面例子:

package com.wyw.io;
import java.io.*;
public class IOUtil {
    /**
     * 用字节流,从一个文件中拷贝一个文件到另一个文件夹下(文件下载/上传),此方法比缓冲流要快
     * IOUtil.copyFile(new File("E:/java/基础内容总结.txt"),new File("E:/java/z20161023/1.txt"));需要注意目标路径后面要加原文件的后缀,不可不写
     * @param rootPath   
     * @param targetPath
     */
    public static void copyFile(File rootPath,File targetPath)throws IOException{
        FileInputStream in = new FileInputStream(rootPath);
        FileOutputStream out = new FileOutputStream(targetPath);
        byte[] buf = new byte[8*1024];
        int len;
        while((len=in.read(buf,0,buf.length))!=-1){
            out.write(buf, 0, len);
            out.flush();
        }
        in.close();
        out.close();
    }
    /**
     * 用缓冲流把一个文件拷贝到另一个文件夹下,(相当于文件下载/上传),此方法用时较长
     * IOUtil.copyFile_(new File("E:/java/基础内容总结.txt"),new File("E:/java/z20161023/1.txt"));需要注意目标路径后面要加原文件的后缀,不可不写
     * @param rootPath
     * @param targetPath
     */
    public static void copyFile_(File rootPath,File targetPath)throws Exception{
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(rootPath));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetPath));
        int len ;
        while((len=bis.read())!=-1){
            bos.write(len);
            bos.flush();
        }
        bis.close();
        bos.close();
    }
    /**
     * 从一个文档中读取内容写入另一个文本文档中,此方法每次读取一行速度较快
     * @param rootPath
     * @param targetPath
     */
    public static void readAndWriteTxt(File rootPath,File targetPath) throws Exception{
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(rootPath),"gbk"));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetPath),"gbk"));
            String str = null;    
            while((str=br.readLine())!=null){
                bw.write(str+"\n");
                //bw.append(str+"\n");
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            br.close();
            bw.close();
        }
    }
    /**
     * 读取文本文档中的内容写入另一个文本文档中,此方法速度较慢,,原因未知
     * @param rootPath
     * @param targetPath
     */
    public static void readAndWtiteTxt_(File rootPath,File targetPath)throws IOException{
        InputStreamReader in = new InputStreamReader(new FileInputStream(rootPath),"gbk");
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(targetPath),"gbk");
        int len ;
        char[] buf = new char[8*1024];
        while((len=in.read(buf,0,buf.length))!=-1){
            out.write(buf,0,buf.length);
            out.flush();
        }
        in.close();
        out.close();
    }
    
}

 

posted @ 2017-04-09 17:18  青春不打烊  阅读(117)  评论(0编辑  收藏  举报