读取单个字节public abstract int read ( ) throws IOException;
读取数据类似于用勺子舀米饭吃。每次读取一次就相当于舀饭。public int read(byte[] b) throws Exception{}如果开辟数组的大小大于了读取的数据的大小,则返回的是读取个数。如果要读取的数据大于数组的内容,则返回数组的长度如果没有数据了,还在继续读取的时候,则会返回-1public int read (byte[] b,int off,int len)throws Exception{}读取数据组的部分内容,如果读取满了,则返回的就是长度len,如果没有读取满,则返回的是读取的数据的个数,如果没有数据了,就返回-1public abstract int read ( ) throws IOException;返回读取内容。InputStream是一个抽象类。类似于OutputStramimport
java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;public class TestDemo{
public static void main(String[] args) throws Exception{
File file=new File("e:"+File.separator+"hello.txt");
if(file.exists()) {//保证文件存在
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();
}
}
}
字符输出流 write, write 最适合中文的处理 里面有一个输出字符串的方法public void write()操作文件使用FileWrite 子类通过 write 来输出
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.Writer;public class TestDemo{
public static void main(String[] args) throws Exception{
File file=new File("e:"+File.separator+"hello.txt");
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
String msg="世界和平";
Writer out=new FileWriter(file);
out.write(msg);
out.close();
}
}
outputstream 的结构和write 的结构很像
字符输入流 ReaderReader 也是抽象类,要实现文件读取,要用FileReader 子类。charbufferreadable 接口,在IO接口中,先处理的是字节流,再字符流。writer 可以输出字符串,但是reader没有方法直接读取数据为字符串。比如一个大文件,按照String方式读取的时候,会内存不足。通过文件读取数据 Reader
import java.io.File;
import java.io.FileReader;
import java.io.Reader;public class TestDemo{
public static void main(String[] args) throws Exception{
File file=new File("e:"+File.separator+"hello.txt");
if(file.exists()) {//保证文件存在,进而读取文件
Reader in=new FileReader(file);
char date[]=new char[1024];//定义一个数组长度
int len=in.read(date);//数组长度通过read来获取
System.out.println(new String(date,0,len));//data 中存有文件中的内容
in.close();
}
}
}
字符流在进行读取的时候进行单个数据的读取要比字节更加方便的处理中文,用的最多的还是字节流
主要的区别是不大的,但是在处理中文的时候才会使用到字符流。因为所有的字符都需要用内存缓冲再进行处理当进行数据传输的时候,要分为两个端,一个发送,一个接收。网上传输的都是字节。也就是01码读、写都需要缓存的处理字节输出内容在缓冲中。如果在使用字符流操作时,内容就有可能在缓存之中。所以必须强制刷新才能得到完整的缓冲。{关闭操作后才能输出close()}写上out.flush()就会强制输出。总之,是先放置在缓存中。不论是文件、文字、图片,都可以使用字节流,只有在处理中文的时候,才会使用字符流。