Java中的輸入輸出流

InputStream(OutputStream)

InputStream(OutputStream)每次只能讀寫一個字節(jié)或一個字
節(jié)數(shù)組,若要讀取或者寫入如int,double等數(shù)據(jù)需要自行處理成字
節(jié)再進行讀寫。

FileInputStream為InputStream接口的一個實現(xiàn)類,方便文件
讀取

  • 單字節(jié)讀取
    public static void inputStreamTest(String fileName) throws IOException {
    
            FileInputStream fileInputStream  = new FileInputStream(fileName);
            int i = 0;
            while ((i = fileInputStream.read()) != -1) {
                System.out.print(Integer.toHexString(i) + " ");
            }
            fileInputStream.close();
        }
    
//每次寫入一個字節(jié)
    public static void fileOutputStreamTest(String fileName) throws IOException {

        FileOutputStream out = new FileOutputStream(fileName, true);
        //寫出A字符的低8位
        out.write('A');
        out.write(1);
        out.write("哈嘍".getBytes());


        out.close();
    }
  • 讀取到字節(jié)數(shù)組
    public static void inputStreamTest2(String fileName) throws IOException {
    
            FileInputStream fileInputStream = new FileInputStream(fileName);
            byte[] buf = new byte[1024 * 2];
            int size = 0;
    
            while ((size = fileInputStream.read(buf)) != -1) {
                for (int i = 0; i < size; i++) {
                    if (i % 10 == 0 && i != 0) {
                        System.out.println();
                    }
                    System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");
                }
            }
    
            fileInputStream.close();
    
        }

//每次讀寫一個字節(jié)數(shù)組的數(shù)據(jù)比讀取單個字節(jié)效率高很多
    public static void copyByBytes(File srcFile, File destFile) throws IOException {

        if (!srcFile.exists()) {
            throw new IllegalArgumentException("source file not exists!");
        } else if (!srcFile.isFile()) {
            throw new IllegalArgumentException("source file must be file!");
        }

        FileInputStream inputStream = new FileInputStream(srcFile);
        FileOutputStream outputStream = new FileOutputStream(destFile);

        byte[] buf = new byte[1024 *1024];
        int size = 0;
        while ((size = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, size);
            outputStream.flush();
        }

        inputStream.close();
        outputStream.close();
    }
  • DataInputStream的使用

DataOutputStream(DataInputStream)為InputStream
(OutputStream)提供包裝,方便讀取int,double,UTF等
數(shù)據(jù)類型

    public static void DataInputStreamTest(String fileName) throws IOException {
    
            DataInputStream dataInputStream =
                    new DataInputStream(new FileInputStream(fileName));
    
            System.out.println(dataInputStream.readInt());
            System.out.println(dataInputStream.readDouble());
            System.out.println(dataInputStream.readUTF());
            System.out.println(dataInputStream.readChar());
    
        }
    
    public static void DataOutputStreamTest(String fileName) throws IOException {
    
            DataOutputStream dataOutputStream =
                    new DataOutputStream(new FileOutputStream(fileName));
    
            dataOutputStream.writeInt(1);
            dataOutputStream.writeDouble(1.1);
            dataOutputStream.writeUTF("哈嘍");
            //UTF-16be編碼格式,char占兩個字節(jié)
            dataOutputStream.writeChars("哈哈");
    
            dataOutputStream.close();
    
        }

  • 使用BufferedInputStream

BufferedInputStream提供了緩沖讀取,讀取時判斷是否可以
從該類自帶的緩沖區(qū)中讀取,提高效率。

多次從流中讀取少量字節(jié)時候效率較高

使用read(byte[] b)進行讀取時,若緩沖區(qū)小于b的大小則每次
直接從流中讀取,并更新緩沖區(qū),效率與直接使用InputStream
的read(byte[])相當,若緩沖區(qū)大小大于b,則效率反而會降低

public static void copyByBuffer(File srcFile, File destFile) throws IOException {

        if (!srcFile.exists()) {
            throw new IllegalArgumentException("source file not exists!");
        } else if (!srcFile.isFile()) {
            throw new IllegalArgumentException("source file must be file!");
        }

        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(srcFile));

        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(destFile));

        byte[] buf = new byte[1024 * 1024];

        int c = 0;
        while ((c = bis.read(buf)) != -1) {
            bos.write(buf, 0, c);
        }

        bis.close();
        bos.close();

    }

Reader(Writer)

Reader和Writer簡化了字符的讀寫,可以不用手動對字節(jié)進行
處理,而直接面向字符。

  • InputStreamReader(Writer)
    public static void InputStreamReaderTest(File file) throws IOException {
    
            FileInputStream fi = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(fi);
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("c.txt")));
    
    
            int c = 0;
            char[] buf = new char[1024];
            while ((c = reader.read(buf, 0, buf.length)) != -1){
                String s = new String(buf, 0, c);
                writer.write(s);
                System.out.println(s);
            }
    
            reader.close();
            writer.close();
    
        }
  • FileReader(Writer)

FileReader(Writer)簡化了對文件的字符的讀寫

    public static void fileReaderTest(File file) throws IOException {
    
            FileReader fileReader = new FileReader(file);
            FileWriter fileWriter = new FileWriter("c.txt");
    
            char[] buf = new char[1024];
            int c = 0;
            while ((c = fileReader.read(buf, 0, buf.length)) != -1) {
                fileWriter.write(buf, 0, c);
            }
    
            fileReader.close();
            fileWriter.close();
        }
  • BufferedReader(Writer)

BufferedReader(Writer)對Reader(Writer)進行包裝,簡化
字符的讀寫操作。

    public static void bufferedReaderTest(File file) throws IOException {
    
            BufferedReader br = new BufferedReader(new FileReader(file));
            BufferedWriter bw = new BufferedWriter(new FileWriter("c.txt"));
            //PrintWriter更方便
            PrintWriter pw = new PrintWriter("d.txt");
    
    
            String line = "";
            while ((line = br.readLine()) != null) {
                pw.println(line);
                bw.write(line);
                bw.newLine();//換行
            }
    
    
            br.close();
            bw.close();
            pw.close();
    
        }

ObjectInputStream(OutputStream)

需要實現(xiàn)Serializable接口才能進行序列化

沒有實現(xiàn)Serializable接口的父類,反序列化時構(gòu)造函數(shù)會被調(diào)用

transient關(guān)鍵字指定某個屬性不進行序列化,并手動進行序列化

  • Student類
public class Student implements Serializable{

    private transient int age;
    private String name;

    public Student() {
    }

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    //手動反序列化
    private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();//jvm默認可以反序列化的反序列化
        age = s.readInt();//默認不行的手動反序列化
    }

    //手動序列化
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException{
        s.defaultWriteObject();//jvm默認可以序列化的進行序列化
        s.writeInt(age);//不能序列化的手動序列化
    }
}
  • 序列化操作
public static void objectSeriaTest(Student student) throws IOException, ClassNotFoundException {

        ObjectOutputStream outputStream = new ObjectOutputStream(
                new FileOutputStream("object.txt")
        );

        ObjectInputStream inputStream = new ObjectInputStream(
                new FileInputStream("object.txt")
        );

        outputStream.writeObject(student);
        Student stu = (Student) inputStream.readObject();
        System.out.println(stu);

        outputStream.close();
        inputStream.close();

    }

Reference

文件傳輸基礎(chǔ)——Java IO流

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容