Detailed introduction to byte stream and character stream of I/O stream in Java
一、绪论
如果要进行文件内容的操作那么必须依靠数据流完成,而数据流分为两种:
字节流:InputStream(字节输入流)、OutputStream(字节输出流);
字符流:Reader(字符输入流)、Writer(字符输出流);
二、区别
字节流是原生的操作,而字符流是经过处理后的操作。
在进行网络数据传输、磁盘数据保存所保存所支持的数据类型只有:字节。而所有磁盘中的数据必须先读取到内存后才能进行操作,而内存中会帮助我们把字节变为字符。字符更加适合处理中文。如果处理中文使用字符流,其他的任何数据都使用字节流。
相关学习视频推荐:java学习视频
三、字节输出流:(OutputStream)
OutputStream类定义有三个重要的输出操作方法:
1. 将给定的字节数组内容全部输出:
public void write(byte b[]) throws IOException
2. 将部分字节数组内容输出:(重点)
public void write(byte b[], int off, int len) throws IOException
3. 输出单个字节:
public abstract void write(int b) throws IOException
OutputStream是一个抽象类,按照抽象类的基本原则来讲,如果想要取得OutputStream类的实例化对象那么一定需要子类,如果要进行文件的操作,可以使用FileOutputStream类来处理,这个类的构造方法如下:
1. 接收File类(覆盖):
public FileOutputStream(File file) throws FileNotFoundException
2. 接收File类(追加):
public FileOutputStream(File file, boolean append)
//第一步:定义要输出的文件的File类对象 File file = new File("e:"+File.separator+"hello"+File.separator+"my.txt"); //输出信息的时候文件可以不存在,但是目录必须存在 if(!file.getParentFile().exists()) {//父路径不存在 file.getParentFile().mkdirs();//创建父路径 } //第二步:利用OutputStream的子类为父类进行实例化 OutputStream output = new FileOutputStream(file); //第三步:输出文字信息 String msg = "富则达济天下,穷则独善其身";//字符串 //为了方便输出需要将字符串变为字节数组 byte data[] = msg.getBytes();//变为字节数组 output.write(data);//输出数据 output.close();//关闭流
输出文件的部分内容
output.write(data,0,10);//输出部分数据
使用循环方式进行单个字节的信息输出
for(int x = 0;x < data.length; x++) { output.write(data[x]);//单个字节输出数据 }
但是使用单个字节输出会将之前的内容都被覆盖了。所以需要进行数据的追加操作
OutputStream output = new FileOutputStream(file,true);//此处为追加操作
四、字节输入流:(InputStream)
InputStream类中定义有三个数据的读取操作方法:
1.读取单个字节:
public abstract int read() throws IOException;
每次执行此方法将读取当个字节数据,如果已经读取完成了,那么最后返回-1。
2.读取数据到字节数组中:
public int read(byte b[]) throws IOException.
最常用方法,每次讲数据读取到数组之中,那么会返回一个读取长度的数据,如果没有数据则返回的长度为-1,
可是要考虑两种情况:
要读取的内容大于开辟的数组内容:长度就是整个数组的长度。
要读取的内容小于开辟数组的内容,长度就是全部最后的内容长度,数组装不满。
3.读取部分内容到字节数组中:
public int read(byte b[], int off,int len) throws IOException
每次读取内容到部分字节数组,只允许读取满限制的数组的字节个数。此方法依然会返回读取的长度。
InputStream
是一个抽象类,所以要进行文件的读取使用FileInputStream子类,子类定义的构造方法如下:
构造方法:public FileInputStream(File file) throws FileNotFoundException.
//第一步:定义要输出的文件的File类对象 File file = new File("e:"+File.separator+"hello"+File.separator+"my.txt"); //第二步:实例化InputStream InputStream input = new FileInputStream(file); //实现数据的读取操作 byte data[] = new byte[1024]; int len = input.read(data);//将数据读取到数组之中 System.out.println("读取的内容【" +new String(data,0,len)+"】"); //第四步关闭输入流 input.close();
补充:DataInputStream
和 DataOutputStream
DataInputStream类继承了InputStream。也就是说DataInputStream是InputStream的子类。但它们同是实现了DataInput接口。
DataOutputStream类继承了OutputStream。也就是说DataOutputStream是OutputStream的子类。但它们同是实现了DataOutput接口。
五、字符输出流:(Writer)
Writer是一个抽象类,要进行文件字符流操作可以使用FileWriter类处理,其构造方法为:
public FileWriter(File file)
//第一步:定义要输出的文件的File类对象 File file = new File("e:"+File.separator+"hello"+File.separator+"my.txt");//你的路径 if(!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } Writer out = new FileWriter(file); String str = "一定要好好学习,天天向上。。。"; out.write(str); out.close();
虽然Writer类提供有字符数组的输出操作能力,但是从本质上来讲使用Writer类就意味着要执行字符串的直接输出。字符流最适合操作中文,但并不意味着字节流就无法操作中文。
六、字符输入流:(Reader)
Reader是一个抽象类,要进行文件字符流操作可以使用FileReader类处理,其构造方法为:
public FileReader (File file)
//第一步:定义要输出的文件的File类对象 File file = new File("e:"+File.separator+"hello"+File.separator+"my.txt");//你的路径 if(file.exists()) { Reader in = new FileReader(file); char data[] = new char[1024]; int len = in.read(data);//向字符数组保存数据,返回长度。 System.out.println(new String(data,0,len)); in.close();
七、补充
为了提高字符流读写的效率,引入了缓冲机制,java提供了缓存流类:BufferedInputStream
、BufferedOutputStream
类和BufferedReader
、 BufferedWriter
类
//使用buffer进行文件读写 BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream (new File("D:\\BIGBANG - IF YOU (Live).mp3"))); File newFile = new File("D:\\copyMusic\\BIGBANG - IF YOU (Live).mp3"); newFile.createNewFile(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(newFile)); byte[] bytes= new byte[1024]; int length = 0; while ((length=bufferedInputStream.read(bytes))!=-1){ bufferedOutputStream.write(bytes,0,length); }
相关文章教程推荐:java开发入门
The above is the detailed content of Detailed introduction to byte stream and character stream of I/O stream in Java. For more information, please follow other related articles on the PHP Chinese website!

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor
