欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java SE之IO

程序员文章站 2022-03-04 12:20:57
...
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Kevin 2018-1-10
 * 
 * io操作工具类。读取office(word)内容建议POI,pdf建议iText。
 * 
 * 学习:http://ifeve.com/java-io/
 *
 */
public class IOUtil {

    private static final int DEFAULT_BYTE_SIZE = 1024;

    //can not create object IOUtil
    private IOUtil(){}

    /**
     * 复制文件
     * @param srcPath
     * @param descPath
     */
    private static void copyFile(String srcPath, String descPath) {

        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(new File(srcPath));
            byte[] bytes = new byte[DEFAULT_BYTE_SIZE];

            out = new FileOutputStream(descPath);

            int len = 0;
            while((len = in.read(bytes)) != -1){
                out.write(bytes, 0, len);
            }
        } catch (Exception e) {

        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取文件为字节数组。
     * @param path
     * @return
     */
    public static byte[] readFile2Byte(String path){
        InputStream in = null;

        try {
            in = new FileInputStream(new File(path));
            byte[] bytes = new byte[in.available()];

            int len = 0;
            for(int i = 0;(len=in.read())!=-1;i++){
                bytes[i] = (byte) ((char)len);
            }
            return bytes;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}