package com.qmth.boot.tools.io;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class IOUtils {

    public static final String ZIP_SEPERATOR = "/";

    public static void closeQuietly(FileChannel fc) {
        try {
            if (fc != null) {
                fc.close();
            }
        } catch (IOException e) {
        }
    }

    public static void closeQuietly(InputStream ins) {
        try {
            if (ins != null) {
                ins.close();
            }
        } catch (IOException e) {
        }
    }

    public static void closeQuietly(OutputStream ous) {
        try {
            if (ous != null) {
                ous.close();
            }
        } catch (IOException e) {
        }
    }

    public static long copy(InputStream input, OutputStream output, BufferListener listener) throws IOException {
        long count = 0L;
        int n;
        for (byte[] buffer = new byte[4096]; -1 != (n = input.read(buffer)); count += n) {
            if (output != null) {
                output.write(buffer, 0, n);
            }
            if (listener != null) {
                listener.listen(buffer, n);
            }
        }
        return count;
    }

    public static long copy(InputStream input, OutputStream output) throws IOException {
        return copy(input, output, null);
    }

    public static void copy(File source, File target) throws IOException {
        Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    public static byte[] toByteArray(InputStream ins) throws IOException {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        copy(ins, ous);
        return ous.toByteArray();
    }

    public static byte[] toByteArray(String filePath) throws IOException {
        return toByteArray(new File(filePath));
    }

    public static byte[] toByteArray(File file) throws IOException {
        FileInputStream ins = new FileInputStream(file);
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        copy(ins, ous);
        closeQuietly(ins);
        return ous.toByteArray();
    }
}
