search
HomeJavajavaTutorialHow to implement buffered input and output streams in Java

缓冲是 I/O 的一种性能优化。缓冲流为 I/O 流增加了内存缓冲区。

BufferedInputStream类 与 BufferedOutputStream类

BufferedInputStream类 可以对所有InputStream的子类进行缓冲区的包装,以达到性能的优化。

BufferedOutputStream类 中的 flush()方法 被用来把缓冲区的字节写入到文件中,并清空缓存。

BufferedInputStream类的构造方法:

构造方法 介绍
BufferedInputStream(FileInputStream fileInputStream); 创建一个带有32个字节的缓冲输入流。
BufferedInputStream(FileInputStream fileInputStream , int size); 按指定的大小来创建缓冲输入流。

BufferedOutputStream类的构造方法:

构造方法 介绍
BufferedOutputStream(FileOutputStream fileOutputStream); 创建一个带有32个字节的缓冲输出流。
BufferedOutputStream(FileOutputStream fileOutputStream , int size); 按指定的大小来创建缓冲输出流。

BufferedInputStream类 与 BufferedOutputStream类 实例:

import java.io.*;
 
public class Demo4 {
    public static void main(String[] args) {
        /**
         * 缓冲字节输入流(BufferedInputStream)
         * 特点:提高效率
         */
        File file = new File("C:\\JAVA_API_1.7中文.chm");
        BufferedInputStream bufferedInputStream = null;//创建缓冲字节流
        FileInputStream fileInputStream = null;
        long stare = System.currentTimeMillis();//获得当前流开始时的毫秒值
        try {
            fileInputStream=new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);//将文件字节流包装成缓冲字节流
            byte by[] = new byte[1024];//缓冲区字节数组(这个缓冲区与Buffered不同)
            while ((bufferedInputStream.read(by))!=-1){//使用缓冲字节流读取数据
 
            }
            long end = System.currentTimeMillis();//获得当前流结束时的毫秒值
            System.out.println("运行经历的毫秒数:"+(end - stare));
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream!=null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        
        /**
         * 缓冲字节输出流(BufferedOutputStream)
         * 特点:提高效率
         */
        File file1 = new File("C:\\Word.txt");
        BufferedOutputStream bufferedOutputStream = null;//创建缓冲字节输出流
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream=new FileOutputStream(file1);
            bufferedOutputStream=new BufferedOutputStream(fileOutputStream);//将文件输出流包装到缓冲字节输出流
 
            String str = "深山踏红叶,耳畔闻鹭鸣。";
            byte by[] = str.getBytes();
            bufferedOutputStream.write(by);
            //<*> 使用缓冲字节输出流时,要多进行刷新操作,避免等待,有数据时就将数据写入文件当中 <*>
            bufferedOutputStream.flush();//刷新(强制将缓冲区数据写入文件中,即使缓冲区没有写满)
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream!=null){
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

BufferedReader类 与 BufferedWriter类

BufferedReader类 与 BufferedWriter类 分别继承了 Reader类 与 Writer类,这两个类同样具有内部缓冲机制,并以行为单位输入/输出。

BufferedReader类常用方法:

How to implement buffered input and output streams in Java

BufferedWriter类常用方法:

How to implement buffered input and output streams in Java

BufferedReader类 与 BufferedWriter类 实例:

import java.io.*;
 
public class Demo6 {
    public static void main(String[] args) {
        File file = new File("C:\\Word.txt");
 
        /**
         * 文件缓冲字符输出流(BufferedWriter)
         */
        FileWriter fileWriter = null;//创建文件字符输出流
        BufferedWriter bufferedWriter = null;//创建文件缓冲字符输出流
 
        try {
            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);//将文件字符输出流包装成文件缓冲字符输出流
 
            String str1 = "神里";
            String str2 = "绫华";
 
            bufferedWriter.write(str1);//第一行数据
            bufferedWriter.newLine();//创建一个新行
            bufferedWriter.write(str2);//第二行数据
 
        } catch (IOException e) {
            e.printStackTrace();
        }finally {//<*> 注意:流的关闭顺序,先创建的后关闭。 <*>
            if (bufferedWriter!=null){
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
 
        /**
         * 文件缓冲字符输入流(BufferedReader)
         */
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);//将文件字符输入流包装成文件缓冲字符输入流
            String tmp = null;//临时变量
            int i = 1;//计数器
            while ((tmp = bufferedReader.readLine())!=null){//循环读取文件中的内容
                System.out.println("第"+i+"行:"+tmp);
                i++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileReader!=null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

The above is the detailed content of How to implement buffered input and output streams in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use