2019-08-25

2019-08-25  本文已影响0人  勿陌

IO工具类,记录日志


import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Title:IOUtils
 * Description::io�����࣬�ر�������
 * 
 * @author ̷��
 * @date 2019��4��25��
 */
public class IOUtils {

    private static Reader isr;

    public static void makeDirectory(String path) {
        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void log(String str) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = df.format(System.currentTimeMillis());
        str = time + "  " + str + "\r\n";
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream("Log.txt", true);
            bos = new BufferedOutputStream(fos);
            byte[] b = str.getBytes();
            bos.write(b);
            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(fos, bos);
        }
    }

    public static String file2String(String file) {
        File fil = new File(file);
        if (file.isEmpty()) {
            return null;
        }
        try {
            isr = new InputStreamReader(new FileInputStream(fil), "utf-8");
            int len = 0;
            char[] data = new char[1024 * 1024];
            while ((len = isr.read(data)) > 0) {
                String str = new String(data, 0, len);
                close(isr);
                return str;
            }
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        close(isr);
        return null;
    }

    public static void close(Closeable... closeable) {
        for (Closeable closeable2 : closeable) {
            if (closeable2 != null) {
                try {
                    closeable2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
上一篇 下一篇

猜你喜欢

热点阅读