1. 程式人生 > 實用技巧 >IO流學習

IO流學習

IO框架

流的概念

記憶體與儲存裝置之間傳輸資料的通道

流的分類

輸入流:儲存裝置==========>記憶體

輸出流:儲存裝置<==========記憶體

位元組流:以位元組為單位,可以讀寫所有資料

字元流:以字元為單位,只能讀寫文字資料

節點流:具有實際傳輸資料的讀寫功能

過濾流:在節點流的基礎上增強功能

位元組流

位元組流的父類(抽象類):

FileInputStream:位元組輸入流

public class Demo01 {
    public static void main(String[] args) throws IOException {
        //建立檔案位元組輸入流,指定檔案路徑
        FileInputStream fileInputStream = new FileInputStream("E:\\Java學習\\inputexample.txt");
        //單個位元組讀取檔案
        //int data = 0;
        //while ((data = fileInputStream.read()) != -1){
           //System.out.print((char) data);
        //}
        //System.out.println("");
        //System.out.println("執行結束");
        //一次性讀取多個位元組
        byte[] buf = new byte[2];
        int count = 0;
        while ((count = fileInputStream.read(buf)) != -1){
            System.out.print(new String(buf,0,count));
        }
    }
}

FileOutputStream:位元組輸出流

public class Demo02 {
    public static void main(String[] args) throws Exception{
        //建立檔案位元組流輸出物件
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\Java學習\\IO框架\\example.txt",true);
        fileOutputStream.write(3);
        fileOutputStream.write('9');
        fileOutputStream.write(38);
        String b = "What are you talking about?";
        fileOutputStream.write(b.getBytes());
        fileOutputStream.close();
        System.out.println("The end.");
    }
}

利用位元組輸入流和位元組輸出流複製檔案(檔案型別不受限)

public class Demo03 {
    public static void main(String[] args) throws Exception{
        //檔案位元組輸入流
        FileInputStream fileInputStream = new FileInputStream("E:\\Java學習\\IO框架\\微信截圖_20200706105652.png");
        //檔案位元組輸出流
        FileOutputStream fos = new FileOutputStream("E:\\Java學習\\IO框架\\複製微信截圖_20200706105652.png");
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = fileInputStream.read(buf)) != -1){
            fos.write(buf,0,count);//寫入一個位元組的內容
        }
        System.out.println("複製結束");
        fileInputStream.close();
        fos.close();
    }
}

BufferInputStream/BufferOutputStream:位元組緩衝流

提高I/O效率,減少訪問磁碟的次數;資料儲存在緩衝區中,flush是將快取區的內容寫入檔案,也可以直接close

public class Demo04 {
    public static void main(String[] args) throws Exception{
        FileInputStream fis = new FileInputStream("E:\\Java學習\\inputexample.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        //int data = 0;
        //while ((data = bis.read()) != -1){
            //System.out.print((char)data);
        //}
        //bis.close();
        byte[] buf =new byte[1024];
        int count = 0;
        while ((count = bis.read(buf)) != -1){
            System.out.print(new String(buf,0,count));
        }
        bis.close();
    }
}
public class Demo05 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos = new FileOutputStream("E:\\Java學習\\IO框架\\BufferOutputStream.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        for (int i = 0; i < 10; i++) {
            bos.write("100100001101010\r\n".getBytes());//寫入了8K的緩衝區
            bos.flush();//重新整理到硬盤裡
        }
        bos.close();
    }
}

物件流

ObjectInputStream/ObjectOutpuStream

​ 增強了快取區功能

​ 增強了八種基本資料型別和字串功能

​ 增強了讀寫物件的功能:

readObject() 從流中讀取一個物件 反序列化

writeObject() 向流中寫入一個物件 序列化

程式碼例項

public class Star implements Serializable {

    //serialVersionUID 序列化版本ID 保證序列化的類和反序列化的類是同一個類
    //使用transient來修飾屬性,則該屬性不能序列化
    private int month;
    private String name;

    public Star() {
    }

    public Star(int month, String name) {
        this.month = month;
        this.name = name;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Star{" +
                "month=" + month +
                ", name='" + name + '\'' +
                '}';
    }
}
public class Demo06 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos = new FileOutputStream("E:\\Java學習\\IO框架\\Star-oos.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //序列化
        Star star1 = new Star(12,"Capricorn");
        Star star2 = new Star(1,"Aquarius");
        ArrayList<Star> stars = new ArrayList<>();
        stars.add(star1);
        stars.add(star2);
        oos.writeObject(stars);
        oos.close();
        System.out.println("序列化結束");
    }
}
public class Demo07 {
    public static void main(String[] args) throws Exception{
        FileInputStream fis = new FileInputStream("E:\\Java學習\\IO框架\\Star-oos.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);

        ArrayList<Star> list = (ArrayList<Star>)ois.readObject();
        System.out.println(list.toString());
        ois.close();
    }
}

字元流

字元編碼

ISO-8859-1

UTF-8

GB2312(95年之前)

GBK

BIG5

字元流的父類(抽象類)

reader:字元輸入流

writer:字元輸出流

檔案字元流FileReader/FileWriter

public class Demo09 {
    public static void main(String[] args) throws Exception{
        FileReader fileReader = new FileReader("E:\\Java學習\\IO框架\\example.txt");
        //System.out.println("=====單個字元讀取");
        //int data = 0;
        //while ((data = fileReader.read()) != -1){
            //System.out.print((char)data);
        //}
        //fileReader.close();
        char[] buf =new char[1024];
        int count = 0;
        while ((count = fileReader.read(buf)) != -1){
            System.out.print(new String(buf,0,count));
        }
        fileReader.close();
    }
}
public class Demo10 {
    public static void main(String[] args) throws Exception{
        FileWriter fileWriter = new FileWriter("E:\\Java學習\\IO框架\\輸入字元流.txt");
        for (int i = 0; i < 100; i++) {
            fileWriter.write("在這複雜的世界裡\r\n");
        }
        fileWriter.close();
    }
}

複製檔案的案例:使用字元流只能複製文字檔案,不能複製其他型別的檔案(二進位制檔案、圖片音訊等)

public class Demo11 {
    public static void main(String[] args) throws Exception{
        FileWriter fileWriter = new FileWriter("E:\\Java學習\\IO框架\\字元流複製案例.txt");
        FileReader fileReader = new FileReader("E:\\Java學習\\IO框架\\example.txt");
        int data = 0;
        while ((data = fileReader.read()) != -1){
            fileWriter.write(data);
        }
        fileReader.close();
        fileWriter.close();
    }
}

字元緩衝流

高效讀寫;支援換行符;可以寫一行、讀一行

public class Demo12 {
    public static void main(String[] args) throws Exception{
        FileReader fileReader = new FileReader("E:\\Java學習\\IO框架\\example.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        //自創緩衝區 一個字元一個字元讀取
        //char[] buf =new char[1024];
        //int count = 0;
        //while ((count = bufferedReader.read(buf)) != -1){
            //System.out.print(new String(buf,0,count));
        //}
        //bufferedReader.close();
        String line = null;
        while ((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }
        bufferedReader.close();
    }
}
public class Demo13 {
    public static void main(String[] args) throws Exception{
        FileWriter fileWriter = new FileWriter("E:\\Java學習\\IO框架\\字元緩衝輸入流.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        for (int i = 0; i < 10; i++) {
            bufferedWriter.write("少吃一點!\r\n");
            bufferedWriter.newLine();//寫入一個換行符
            bufferedWriter.flush();
        }
        bufferedWriter.close();
        System.out.println("the mission is over");
    }
}

列印流PrintWriter

public class Demo14 {
    public static void main(String[] args) throws Exception{
        PrintWriter printWriter = new PrintWriter("E:\\Java學習\\IO框架\\列印流.txt");
        printWriter.println(100);
        printWriter.println("love");
        printWriter.println(100.987);
        printWriter.println('b');
        printWriter.close();
    }
}

轉換流InputStreamReader/OutputStreamWriter

可以將位元組流轉換為字元流inputstreamreader/OutputStreamWriter

public class Demo15 {
    public static void main(String[] args) throws Exception{
        FileInputStream fis = new FileInputStream("E:\\Java學習\\IO框架\\example.txt");
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        int data = 0;
        while ((data = isr.read()) != -1){
            System.out.print((char)data);
        }
        isr.close();
    }
}
public class Demo16 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\Java學習\\IO框架\\轉換流.txt");
        OutputStreamWriter gbk = new OutputStreamWriter(fileOutputStream, "gbk");
        for (int i = 0; i < 10; i++) {
            gbk.write("我好累啊\r\n");
            gbk.flush();
        }
        gbk.close();
        System.out.println("執行結束");
    }
}

File類

代表物理碟符中的一個檔案或者一個資料夾

public class Demo01 {
    public static void main(String[] args) throws Exception{
        //separator();
        //fileOpe();
        directorOpe();
    }
    public static void separator(){
        System.out.println("路徑分隔符"+ File.pathSeparator);
        System.out.println("名稱分隔符"+ File.separator);
    }
    public static void fileOpe() throws Exception{
        //建立檔案 createnewFile
        File file = new File("E:\\Java學習\\IO框架\\file.txt");//不寫路徑只寫檔名,則會直接在專案裡建立檔案
        System.out.println(file.toString());
        if (!file.exists()){
            boolean b = file.createNewFile();
            System.out.println("建立結果"+b);
        }
        //刪除檔案
        //1. 直接刪除delete
        //System.out.println("刪除結果"+file.delete());
        //2. 使用jvm退出時刪除
        //file.deleteOnExit();
        //Thread.sleep(5000);

        //獲取檔案資訊
        System.out.println("獲取檔案的絕對路徑:"+file.getAbsolutePath());
        System.out.println("獲取檔案路徑:"+file.getPath());
        System.out.println("獲取檔名稱:"+file.getName());
        System.out.println("獲取檔案父目錄:"+file.getParent());
        System.out.println("獲取檔案長度:"+file.length());
        System.out.println("獲取檔案建立時間:"+new Date(file.lastModified()).toLocaleString());

        //判斷
        System.out.println("是否可寫"+file.canWrite());
        System.out.println("是否是檔案"+file.isFile());
        System.out.println("是否隱藏"+file.isHidden());
    }
    public static void directorOpe() throws  Exception{
        //建立資料夾
        File dir = new File("E:\\Java學習\\IO框架\\file1\\file2\\file3");
        System.out.println(dir.toString());
        if (!dir.exists()){
            //dir.mkdir();//只能建立單級目錄 mkdirs可以建立多級目錄
            System.out.println("建立結果"+dir.mkdirs());
        }

        //獲取資料夾資訊
        System.out.println("獲取絕對路徑:"+dir.getAbsolutePath());
        System.out.println("獲取路徑:"+dir.getPath());
        System.out.println("獲取名稱:"+dir.getName());
        System.out.println("獲取檔案父目錄:"+dir.getParent());
        System.out.println("獲取檔案建立時間:"+new Date(dir.lastModified()).toLocaleString());
        //判斷
        System.out.println("是否是資料夾"+dir.isFile());
        System.out.println("是否隱藏"+dir.isHidden());
        //遍歷資料夾
        File file2 = new File("C:\\Users\\Think\\Desktop\\我愛北極熊");
        String[] files = file2.list();
        System.out.println("---------------");
        for (String s : files) {
            System.out.println(s);
        }


        System.out.println("=================FileFilter介面的使用================");
        File[] files2 = file2.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (pathname.getName().endsWith(".jpg")){
                    return true;
                }
                return false;
            }
        });
        for (File file : files2) {
            System.out.println(file.getName());
        }
        //刪除資料夾
        //直接刪除
        //System.out.println("刪除結果"+dir.delete());//只刪除最底層的目錄,且必須為空目錄
        //JVM刪除
        //dir.deleteOnExit();
        //Thread.sleep(5000);
    }
}

遞迴遍歷/刪除資料夾練習

public class ListDemo {
    public static void main(String[] args) {
        //listdir(new File("E:\\Java學習\\IO框架\\myfiles"));
        deleteDir(new File("E:\\Java學習\\IO框架\\myfiles2"));
    }
    //遞迴遍歷資料夾
    public static void listdir(File dir){
        File[] files = dir.listFiles();
        System.out.println(dir.getAbsolutePath());
        if (files != null && files.length>0){
            for (File file : files) {
                if (file.isDirectory()){
                    listdir(file);
                }else{
                    System.out.println(file.getAbsolutePath());
                }
            }
        }

    }
    //遞迴刪除資料夾
    public static void deleteDir(File dir){
        File[] files = dir.listFiles();
        if (files!=null && files.length>0){
            for (File file : files) {
                if (file.isDirectory()){
                    deleteDir(file);
                }else{
                    System.out.println(file.getAbsolutePath()+"刪除"+file.delete());
                }
            }
        }
        System.out.println(dir.getAbsolutePath()+"刪除"+dir.delete());
    }
}

FileFilter介面

properties

屬性集合

特點:

  1. 儲存屬性名和屬性值
  2. 屬性名和屬性值都是字串型別
  3. 沒有泛型
  4. 和流有關
public class Demo02 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.setProperty("username","Faye");
        properties.setProperty("userage","20");
        System.out.println(properties.toString());
        //遍歷
        //keyset entryset都可以
        //stringpropertynames()
        Set<String> propertyNames = properties.stringPropertyNames();
        for (String propertyName : propertyNames) {
            System.out.println(propertyName+"===="+properties.getProperty(propertyName));
        }
        //和流有關的方法
        //list方法
        PrintWriter printWriter = new PrintWriter("E:\\Java學習\\IO框架\\列印流properties.txt");
        properties.list(printWriter);
        printWriter.close();
        //store儲存
        FileOutputStream fos = new FileOutputStream("E:\\Java學習\\IO框架\\store.properties");
        properties.store(fos,"註釋");
        fos.close();
        //load載入
        Properties properties2 = new Properties();
        FileInputStream fis = new FileInputStream("E:\\Java學習\\IO框架\\store.properties");
        properties2.load(fis);
        System.out.println(properties2.toString());
    }
}