当前位置 : 主页 > 编程语言 > java >

CS-FileUtils

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package cn.huawei.com.CompressedSeacher.util;i
gistfile1.txt
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.huawei.com.CompressedSeacher.util;
import cn.huawei.com.CompressedSeacher.view.com.impl.FileListTableImpl;
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.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * **
 *
 * @author l00358914
 */
public class FileUtils {
    private static FileUtils instance = new FileUtils();
    private FileUtils() {
    }
    public static FileUtils getInstance() {
        return instance;
    }
    private static StringBuffer sb = new StringBuffer();
    /**
     * 将文本文件中的内容读入到buffer中
     *
     * @param buffer   buffer
     * @param filePath 文件路径
     * @throws IOException 异常
     * @author cn.outofmemory
     * 
     */
    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; // 用来保存每行读取的内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine(); // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line); // 将读到的内容添加到 buffer 中
            buffer.append("\n"); // 添加换行符
            line = reader.readLine(); // 读取下一行
        }
        reader.close();
        is.close();
    }
    /**
     * 读取文本文件内容
     *
     * @param filePath 文件所在路径
     * @return 文本内容
     * @throws IOException 异常
     * @author cn.outofmemory
     * 
     */
    public static String readFile(String filePath) throws IOException {
        StringBuffer sb = new StringBuffer();
        FileUtils.readToBuffer(sb, filePath);
        return sb.toString();
    }
    public static void fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * **
     * java IO方式
     *
     * @param f1
     * @param f2
     * @return
     * @throws Exception
     */
    public static long copyFile_IO(File f1, File f2) throws Exception {
        long time = new Date().getTime();
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(f2);
        byte[] buffer = new byte[length];
        while (true) {
            int ins = in.read(buffer);
            if (ins == -1) {
                in.close();
                out.flush();
                out.close();
                return new Date().getTime() - time;
            } else {
                out.write(buffer, 0, ins);
            }
        }
    }
    /**
     * **
     * 使用NIO中的管道到管道传输
     *
     * @param f1
     * @param f2
     * @return
     * @throws Exception
     */
    public static long copyFile_NIO2Channel(File f1, File f2) throws Exception {
        long time = new Date().getTime();
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(f2);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        int i = 0;
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                return new Date().getTime() - time;
            }
            if ((inC.size() - inC.position()) < 20971520) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 20971520;
            }
            inC.transferTo(inC.position(), length, outC);
            inC.position(inC.position() + length);
            i++;
        }
    }
   /****
    * 
    * 
    * @param f1
    * @param f2
    * @return
    * @throws Exception 
    */
    public static long copyFile_memoryImage(File f1, File f2) throws Exception {
        long time = new Date().getTime();
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        RandomAccessFile out = new RandomAccessFile(f2, "rw");
        FileChannel inC = in.getChannel();
        MappedByteBuffer outC = null;
        MappedByteBuffer inbuffer = null;
        byte[] b = new byte[length];
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.force();
                out.close();
                return new Date().getTime() - time;
            }
            if ((inC.size() - inC.position()) < length) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 20971520;
            }
            b = new byte[length];
            inbuffer = inC.map(MapMode.READ_ONLY, inC.position(), length);
            inbuffer.load();
            inbuffer.get(b);
            outC = out.getChannel().map(MapMode.READ_WRITE, inC.position(), length);
            inC.position(b.length + inC.position());
            outC.put(b);
            outC.force();
        }
    }
    /**
     * **
     * 管道对管道
     *
     * @param f1
     * @param f2
     * @return
     * @throws Exception
     */
    public static long copyFile_Channel2Channel(File f1, File f2) throws Exception {
        long time = new Date().getTime();
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(f2);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        ByteBuffer b = null;
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                return new Date().getTime() - time;
            }
            if ((inC.size() - inC.position()) < length) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 2097152;
            }
            b = ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }
    /**
     * 循环创建父目录,正则表达式方式
     *
     * @param outFileName
     */
    public static void createFatherDir(String outFileName) {
        // 匹配分隔符
        Pattern p = Pattern.compile("[/\\" + File.separator + "]");
        Matcher m = p.matcher(outFileName);
        // 每找到一个匹配的分隔符,则创建一个该分隔符以前的目录
        while (m.find()) {
            int index = m.start();
            String subDir = outFileName.substring(0, index);
            File subDirFile = new File(subDir);
            if (!subDirFile.exists()) {
                subDirFile.mkdir();
                System.out.println("目录创建完成:" + subDir);
            }
        }
    }
    public static void main(String[] args) {
        try {
            createFatherDir("D:\\decompileFolder\\tomcat-websocket.src\\META-INF\\test\\huawei\\web-fragment.xml");
            fileChannelCopy(new File("D:\\decompileFolder\\tomcat-websocket.jar\\META-INF\\web-fragment.xml"), new File("D:\\decompileFolder\\tomcat-websocket.src\\META-INF\\test\\huawei\\web-fragment.xml"));
//            copyFile_NIO2Channel(new File("D:\\decompileFolder\\tomcat-websocket.jar\\META-INF/web-fragment.xml"),new File("D:\\decompileFolder\\tomcat-websocket.src\\META-INF/web-fragment.xml"));
//            copyFile_memoryImage(new File("D:\\decompileFolder\\tomcat-websocket.jar\\META-INF/web-fragment.xml"),new File("D:\\decompileFolder\\tomcat-websocket.src\\META-INF/web-fragment.xml"));
//            copyFile_Channel2Channel(new File("D:\\decompileFolder\\tomcat-websocket.jar\\META-INF/web-fragment.xml"),new File("D:\\decompileFolder\\tomcat-websocket.src\\META-INF/web-fragment.xml"));
        } catch (Exception ex) {
            Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
网友评论