最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java各種流的常見使用方法及示例

 更新時(shí)間:2026年03月03日 10:14:37   作者:tjh510623!  
在java中所有數(shù)據(jù)都是使用流讀寫的,流是一組有序的數(shù)據(jù)序列,將數(shù)據(jù)從一個(gè)地方帶到另一個(gè)地方,這篇文章主要介紹了java各種流的常見使用方法及示例的相關(guān)資料,需要的朋友可以參考下

流在 Java I/O 操作中扮演著核心角色,主要用于處理數(shù)據(jù)序列(如文件、網(wǎng)絡(luò)連接、內(nèi)存緩沖區(qū)等)。它們主要分為兩大類:字節(jié)流字符流。

核心概念

  • 字節(jié)流: 以字節(jié)為單位進(jìn)行讀寫操作 (8-bit),適用于所有類型的數(shù)據(jù)(圖片、音頻、視頻、文本等)。基類是 InputStreamOutputStream。
  • 字符流: 以字符為單位進(jìn)行讀寫操作 (16-bit),專為處理文本數(shù)據(jù)設(shè)計(jì),能正確處理字符編碼(如 UTF-8, GBK)。基類是 ReaderWriter。

常用流類及示例

1. 文件字節(jié)流 (FileInputStream / FileOutputStream)

  • 用途: 讀寫文件中的原始字節(jié)數(shù)據(jù)。
  • 示例: 復(fù)制文件
import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        try (InputStream in = new FileInputStream("source.jpg");
             OutputStream out = new FileOutputStream("copy.jpg")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            System.out.println("文件復(fù)制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 緩沖字節(jié)流 (BufferedInputStream / BufferedOutputStream)

  • 用途: 包裝其他字節(jié)流,提供緩沖區(qū),減少物理 I/O 次數(shù),顯著提升性能。強(qiáng)烈推薦使用!
  • 示例: 高效讀取文件
import java.io.*;

public class BufferedRead {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("data.bin");
             BufferedInputStream in = new BufferedInputStream(fis)) {
            int data;
            while ((data = in.read()) != -1) {
                // 處理每個(gè)字節(jié) data
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 數(shù)據(jù)流 (DataInputStream / DataOutputStream)

  • 用途: 讀寫 Java 基本數(shù)據(jù)類型 (int, double, boolean, String 等) 的二進(jìn)制表示。
  • 示例: 寫入并讀取基本數(shù)據(jù)類型
import java.io.*;

public class DataStreamDemo {
    public static void main(String[] args) {
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) {
            dos.writeInt(100);
            dos.writeDouble(3.14);
            dos.writeBoolean(true);
            dos.writeUTF("你好");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"))) {
            int i = dis.readInt();
            double d = dis.readDouble();
            boolean b = dis.readBoolean();
            String s = dis.readUTF();
            System.out.println(i + ", " + d + ", " + b + ", " + s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. 對(duì)象流 (ObjectInputStream / ObjectOutputStream)

  • 用途: 讀寫實(shí)現(xiàn)了 Serializable 接口的 Java 對(duì)象的序列化/反序列化。
  • 示例: 序列化對(duì)象到文件
import java.io.*;

class Person implements Serializable {
    private String name;
    private transient int age; // transient 修飾的字段不會(huì)被序列化

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // ... Getters, Setters, toString ...
}

public class ObjectStreamDemo {
    public static void main(String[] args) {
        Person person = new Person("張三", 30);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
            Person readPerson = (Person) ois.readObject();
            System.out.println(readPerson); // 注意 age 字段為默認(rèn)值 0 (未序列化)
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

5. 文件字符流 (FileReader / FileWriter)

  • 用途: 讀寫文本文件內(nèi)容,按字符處理。注意編碼問題! 默認(rèn)使用平臺(tái)默認(rèn)編碼。
  • 示例: 讀取文本文件
import java.io.*;

public class FileReadWrite {
    public static void main(String[] args) {
        try (Reader reader = new FileReader("input.txt");
             Writer writer = new FileWriter("output.txt")) {
            char[] buffer = new char[1024];
            int charsRead;
            while ((charsRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, charsRead);
            }
            System.out.println("文本文件復(fù)制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6. 緩沖字符流 (BufferedReader / BufferedWriter)

  • 用途: 包裝其他字符流,提供緩沖區(qū)和便捷方法(如 readLine() 讀取整行文本)。提升文本處理效率。
  • 示例: 逐行讀取文本文件
import java.io.*;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7. 轉(zhuǎn)換流 (InputStreamReader / OutputStreamWriter)

  • 用途: 橋梁作用! 將字節(jié)流轉(zhuǎn)換為字符流,并可顯式指定字符編碼。解決亂碼問題的關(guān)鍵。
  • 示例: 按指定編碼讀取文件
import java.io.*;

public class EncodingDemo {
    public static void main(String[] args) {
        try (InputStream fis = new FileInputStream("input_gbk.txt");
             // 將字節(jié)流 fis 轉(zhuǎn)換為字符流,并指定編碼為 GBK
             Reader isr = new InputStreamReader(fis, "GBK");
             BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line); // 正確顯示 GBK 編碼的中文
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

8. 打印流 (PrintStream / PrintWriter)

  • 用途: 提供方便的打印方法 (print, println, printf),自動(dòng)將各種類型的數(shù)據(jù)轉(zhuǎn)換為文本輸出。System.out 就是一個(gè) PrintStream。
  • 示例: 格式化輸出到文件
import java.io.*;

public class PrintWriterDemo {
    public static void main(String[] args) {
        try (PrintWriter pw = new PrintWriter(new FileWriter("log.txt"))) {
            pw.println("日志開始:");
            pw.printf("時(shí)間: %tT%n", System.currentTimeMillis());
            pw.println("操作: 用戶登錄");
            pw.println("日志結(jié)束.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

9. 管道流 (PipedInputStream / PipedOutputStream / PipedReader / PipedWriter)

  • 用途: 實(shí)現(xiàn)線程間的通信。一個(gè)線程通過 PipedOutputStream/PipedWriter 寫入數(shù)據(jù),另一個(gè)線程通過對(duì)應(yīng)的 PipedInputStream/PipedReader 讀取數(shù)據(jù)。必須連接使用!
  • 示例: 線程間通信
import java.io.*;

public class PipedStreamDemo {
    public static void main(String[] args) throws IOException {
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos); // 連接管道

        Thread writerThread = new Thread(() -> {
            try (DataOutputStream dos = new DataOutputStream(pos)) {
                dos.writeUTF("Hello from writer thread!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Thread readerThread = new Thread(() -> {
            try (DataInputStream dis = new DataInputStream(pis)) {
                String message = dis.readUTF();
                System.out.println("Reader thread received: " + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        writerThread.start();
        readerThread.start();
    }
}

總結(jié)與選擇建議

流類型典型類主要用途特點(diǎn)/注意點(diǎn)
字節(jié)流FileInputStream, FileOutputStream原始字節(jié)數(shù)據(jù)讀寫基礎(chǔ)文件操作
BufferedInputStream, BufferedOutputStream提高字節(jié)流效率強(qiáng)烈推薦包裝使用
DataInputStream, DataOutputStream讀寫基本數(shù)據(jù)類型二進(jìn)制格式
ObjectInputStream, ObjectOutputStream對(duì)象序列化/反序列化對(duì)象需實(shí)現(xiàn) Serializable
PipedInputStream, PipedOutputStream線程間字節(jié)通信必須成對(duì)連接
字符流FileReader, FileWriter文本文件讀寫注意編碼(默認(rèn)平臺(tái)編碼)
BufferedReader, BufferedWriter提高字符流效率,支持readLine()推薦用于文本處理
InputStreamReader, OutputStreamWriter字節(jié)流->字符流轉(zhuǎn)換,指定編碼解決亂碼的關(guān)鍵
PrintStream, PrintWriter格式化打印輸出System.outPrintStream
PipedReader, PipedWriter線程間字符通信必須成對(duì)連接

選擇原則:

  1. 數(shù)據(jù)類型: 處理二進(jìn)制數(shù)據(jù)(圖片、音頻等)用字節(jié)流;處理文本數(shù)據(jù)優(yōu)先考慮字符流。
  2. 性能: 使用 BufferedXxx 包裝流提高效率。
  3. 功能: 根據(jù)需求選擇特定功能的流(如讀寫基本類型用 DataXxx,序列化用 ObjectXxx)。
  4. 編碼: 處理文本時(shí),務(wù)必關(guān)注編碼。使用 InputStreamReader/OutputStreamWriter 明確指定編碼。
  5. 資源管理: 使用 try-with-resources 語句確保流正確關(guān)閉,避免資源泄漏。

總結(jié)

到此這篇關(guān)于java各種流的常見使用方法及示例的文章就介紹到這了,更多相關(guān)java常用流類示例內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

普陀区| 思南县| 大连市| 柞水县| 包头市| 满城县| 宜兰市| 三都| 武定县| 桂阳县| 永春县| 两当县| 连城县| 德保县| 新龙县| 若羌县| 师宗县| 巴林右旗| 湄潭县| 平山县| 宁海县| 龙井市| 大悟县| 民权县| 阜阳市| 临汾市| 桃园市| 韶山市| 阿拉善左旗| 临夏县| 保定市| 徐水县| 义马市| 宣汉县| 武宣县| 高邑县| 信宜市| 阜城县| 宁津县| 东台市| 桂林市|