Java IO與NIO總結

1.File類:用來描述文件和目錄,並提供一些操做,如判斷是否存在,建立等。java

2.流分爲字節流和字符流,InputStream、OutputStream、Reader、Writer四個抽象類apache

字節流以byte爲單位操做數據,字符流以char爲單位操做數據(不一樣編碼的char佔的字節數不一樣,Java使用的是Unicode,char佔兩個byte)設計模式

3.FileInputStream、FileOutputStream以字節爲單位操做文件工具

4.FileReader、FileWriter以默認字符集,以字符爲單位操做文件編碼

FileReader和FileWriter並不是直接繼承自Reader和Writer抽象類,而是直接繼承自InputStreamReader和OutputStreamWriter,這兩個類是字節流和字符流之間轉換的橋樑。FileReader等價於一個FileInputStream加上指定編碼,而後用InputStreamReader轉換設計

5.若是想用指定的字符集操做,能夠使用InputStreamReader、OuterStreamWriter。code

6.字符流 = 字節流 + 編碼,字符流創建在字節流之上。對象

7.緩衝流:避免對一個字節寫一個字節這種低效率操做繼承

Java流若是操做的是文件,類名中通常都帶有File,Java流操做的不必定是文件,好比StringReaderip

緩衝流接收一個流對象,和文件流並無直接關係,他們都是繼承自基本流類;

8.裝飾設計模式

9.ByteArrayInputStream、ByteArrayOutputStream

10.CharArrayReader、CharArrayWriter

11.DataInputStream、DataOutputStream

12.ObjectInputStream、ObjectOutputStream

13.StringReader、StringWriter

 

使用File.separator作文件路徑分割符,能夠在Windows和Linux系統中兼容

將文件流寫入磁盤

從磁盤文件獲取文件流

字節流分組讀取和寫入

字符流按行寫入

字節流與字符流轉換器

磁盤存儲的是字節數據,爲何須要字符流

緩衝流

自定義文件操做工具類

import org.apache.log4j.Logger;

import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/*
 * 文件操做工具類
 */
public class FileUtil {

    private static final Logger log = Logger.getLogger(FileUtil.class);

    /*
     * 建立目錄
     *
     * @param dir 目錄
     */
    public static void mkdir(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
        } catch (Exception e) {
            log.error("建立目錄操做出錯: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /*
     * 新建文件
     *
     * @param fileName String 包含路徑的文件名 如:E:\phsftp\src\123.txt
     * @param content  String 文件內容
     */
    public static void createNewFile(String fileName, String content) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileWriter fw = new FileWriter(filePath);
            PrintWriter pw = new PrintWriter(fw);
            String strContent = content;
            pw.println(strContent);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            log.error("新建文件操做出錯: " + e.getMessage());
            e.printStackTrace();
        }

    }

    /*
     * 刪除文件
     *
     * @param fileName 包含路徑的文件名
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            File delFile = new File(filePath);
            delFile.delete();
        } catch (Exception e) {
            log.error("刪除文件操做出錯: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /*
     * 刪除文件夾
     *
     * @param folderPath 文件夾路徑
     */
    public static void delFolder(String folderPath) {
        try {
            // 刪除文件夾裏面全部內容
            delAllFile(folderPath);
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            // 刪除空文件夾
            myFilePath.delete();
        } catch (Exception e) {
            log.error("刪除文件夾操做出錯" + e.getMessage());
            e.printStackTrace();
        }
    }


    /*
     * 刪除文件夾裏面的全部文件
     *
     * @param path 文件夾路徑
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] childFiles = file.list();
        File temp = null;
        for (int i = 0; i < childFiles.length; i++) {
            //File.separator與系統有關的默認名稱分隔符
            //在UNIX系統上,此字段的值爲'/';在Microsoft Windows系統上,它爲 '\'。
            if (path.endsWith(File.separator)) {
                temp = new File(path + childFiles[i]);
            } else {
                temp = new File(path + File.separator + childFiles[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + childFiles[i]);// 先刪除文件夾裏面的文件
                delFolder(path + "/" + childFiles[i]);// 再刪除空文件夾
            }
        }
    }

    /*
     * 複製單個文件
     *
     * @param srcFile 包含路徑的源文件 如:E:/phsftp/src/abc.txt
     * @param dirDest 目標文件目錄;若文件目錄不存在則自動建立  如:E:/phsftp/dest
     * @throws IOException
     */
    public static void copyFile(String srcFile, String dirDest) {
        try {
            copyFile(srcFile,dirDest,new File(srcFile).getName());
        } catch (Exception e) {
            log.error("複製文件操做出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }


    /*
     * 複製單個文件
     *
     * @param srcFile      包含路徑的源文件 如:E:/phsftp/src/abc.txt
     * @param dirDest      目標文件目錄;若文件目錄不存在則自動建立  如:E:/phsftp/dest
     * @param destFileName 文件名 eg:abc.txt
     * @throws IOException
     */
    public static void copyFile(String srcFile, String dirDest, String destFileName) {

        try {

            FileInputStream in = new FileInputStream(srcFile);
            mkdir(dirDest);
            FileOutputStream out = new FileOutputStream(dirDest + File.separator + destFileName);

            copyStream(in, out);
        } catch (Exception e) {
            log.error("複製文件操做出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }


    /*
     * 複製io流
     *
     * @param in  輸入流
     * @param out 輸出流
     * @throws IOException
     */
    public static void copyStream(InputStream in, OutputStream out) {

        try {

            int len;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            log.error("複製文件操做出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /*
     * 複製流,到文件中
     *
     * @param in
     * @param destFile
     */
    public static void copyInputStreamToFile(InputStream in, File destFile) {

        try {

            FileOutputStream out = new FileOutputStream(destFile);
            copyStream(in, out);
        } catch (Exception e) {
            log.error("複製文件操做出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }


    /*
     * 複製文件夾
     *
     * @param oldPath String 源文件夾路徑 如:E:/phsftp/src
     * @param newPath String 目標文件夾路徑 如:E:/phsftp/dest
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {

            // 若是文件夾不存在 則新建文件夾
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + File.separator + files[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 若是是子文件夾
                    copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
                }
            }
        } catch (Exception e) {
            log.error("複製文件夾操做出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /*
     * 移動文件到指定目錄
     *
     * @param oldPath 包含路徑的文件名 如:E:/phsftp/src/ljq.txt
     * @param newPath 目標文件目錄 如:E:/phsftp/dest
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    /*
     * 移動文件到指定目錄,不會刪除文件夾
     *
     * @param oldPath 源文件目錄  如:E:/phsftp/src
     * @param newPath 目標文件目錄 如:E:/phsftp/dest
     */
    public static void moveFiles(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delAllFile(oldPath);
    }

    /*
     * 移動文件到指定目錄,會刪除文件夾
     *
     * @param oldPath 源文件目錄  如:E:/phsftp/src
     * @param newPath 目標文件目錄 如:E:/phsftp/dest
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }


    /*
     * 壓縮文件
     *
     * @param srcDir  壓縮前存放的目錄
     * @param destDir 壓縮後存放的目錄
     * @throws Exception
     */
    public static void yaSuoZip(String srcDir, String destDir) throws Exception {
        String tempFileName = null;
        byte[] buf = new byte[1024 * 2];
        int len;
        //獲取要壓縮的文件
        File[] files = new File(srcDir).listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    if (destDir.endsWith(File.separator)) {
                        tempFileName = destDir + file.getName() + ".zip";
                    } else {
                        tempFileName = destDir + "/" + file.getName() + ".zip";
                    }
                    FileOutputStream fos = new FileOutputStream(tempFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    ZipOutputStream zos = new ZipOutputStream(bos);// 壓縮包

                    ZipEntry ze = new ZipEntry(file.getName());// 壓縮包文件名
                    zos.putNextEntry(ze);// 寫入新的ZIP文件條目並將流定位到條目數據的開始處

                    while ((len = bis.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                        zos.flush();
                    }
                    bis.close();
                    zos.close();

                }
            }
        }
    }


    /*
     * 讀取數據
     *
     * @param inSream
     * @param charsetName
     * @return
     * @throws Exception
     */
    public static String readData(InputStream inSream, String charsetName) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inSream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();
        return new String(data, charsetName);
    }

    /*
     * 一行一行讀取文件,適合字符讀取,若讀取中文字符時會出現亂碼
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static Set<String> readFile(String path) throws Exception {
        Set<String> datas = new HashSet<String>();
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        String line = null;
        while ((line = br.readLine()) != null) {
            datas.add(line);
        }
        br.close();
        fr.close();
        return datas;
    }
}
相關文章
相關標籤/搜索