Java输入输入流和输出流的区别问题

总结的很粗糙,以后时间富裕了好好修改一下。
1:Java语言定义了许多类专门负责各种方式的输入或者输出,这些类都被放在java.io包中。其中,
所有输入流类都是抽象类InputStream(字节输入流),或者抽象类Reader(字符输入流)的子类;
而所有输出流都是抽象类OutputStream(字节输出流)或者Writer(字符输出流)的子类。
【首先需要明白的是:流是干什么的???(为了永久性的保存数据)
& 根据数据流向的不同分为输入流和输出流;
& 根据处理数据类型的不同分为字符流和字节流;
【然后需要明白的是输入模式和输出模式是谁流向谁:
InputStream(字节输入流)和Reader(字符输入流)通俗的理解都是读(read)的。
OutputStream(字节输出流)和Writer(字符输出流)通俗的理解都是写(writer)的。
最后下面搞清楚各种流的类型的该怎么用,谁包含谁,理清思路。
2:InputStream类是字节输入流的抽象类,是所有字节输入流的父类,InputStream类具有层次结构如下图所示;
3:java中的字符是Unicode编码的,是双字节的。InputStream是用来处理字节的,在处理字符文本时很不方便。Java为字符文本的输入提供了专门的一套类Reader。Reader类是字符输入流的抽象类,所有字符输入流的实现都是它的子类。
4:输出流OutputStream类是字节输入流的抽象类,此抽象类表示输出字节流的所有类的超类。
5:Writer类是字符输出流的抽象类,所有字符输出类的实现都是它的子类。
6:File类是IO包中唯一代表磁盘文件本身的对象。通过File来创建,删除,重命名文件。File类对象的主要作用就是用来获取文本本身的一些信息。如文本的所在的目录,文件的长度,读写权限等等。(有的需要记忆,比如isFile(),isDirectory(),exits();有的了解即可。使用的时候查看API)
详细如下:
File类(File类的概述和构造方法)
A:File类的概述
  File更应该叫做一个路径
  文件路径或者文件夹路径
  路径分为绝对路径和相对路径
    绝对路径是一个固定的路径,从盘符开始
    相对路径相对于某个位置,在eclipse下是指当前项目下,在dos下
  查看API指的是当前路径
  文件和目录路径名的抽象表示形式
B:构造方法
  File(String pathname):根据一个路径得到File对象
  File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
  File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
File类(File类的创建功能)
  A:创建功能
    public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了
    public boolean mkdir():创建文件夹 如果存在这样的文件夹,就不创建了
    public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来
(使用createNewFile()文件创建的时候不加.txt或者其他后缀也是文件,不是文件夹;使用mkdir()创建文件夹的时候,如果起的名字是比如aaa.txt也是文件夹不是文件;)
注意事项:
如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。
File类(File类的重命名和删除功能)
  A:重命名和删除功能
    public boolean renameTo(File dest):把文件重命名为指定的文件路径
    public boolean delete():删除文件或者文件夹
  B:重命名注意事项
    如果路径名相同,就是改名。
    如果路径名不同,就是改名并剪切。
  C:删除注意事项:
    Java中的删除不走回收站。
    要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹
File类(File类的判断功能)
  A:判断功能
    public boolean isDirectory():判断是否是目录
    public boolean isFile():判断是否是文件
    public boolean exists():判断是否存在
    public boolean canRead():判断是否可读
    public boolean canWrite():判断是否可写
    public boolean isHidden():判断是否隐藏
File类(File类的获取功能)
  A:获取功能
    public String getAbsolutePath():获取绝对路径
    public String getPath():获取路径
    public String getName():获取名称
    public long length():获取长度。字节数
    public long lastModified():获取最后一次的修改时间,毫秒值
    public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
    public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
File类(文件名称过滤器的概述及使用)
  A:文件名称过滤器的概述
    public String[] list(FilenameFilter filter)
    public File[] listFiles(FileFilter filter)
1 package com.
3 import java.io.F
5 public class Test {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
File file=new File("aa.txt");//文件默认就创建在你创建的项目下面,刷新即可看到
System.out.println(file.exists());//判断文件是否存在
file.createNewFile();//创建文件,不是文件夹
System.out.println(file.exists());//再次判断是否存在
System.out.println(file.getName());//获取文件的名字
System.out.println(file.getAbsolutePath());//获取文件的绝对路径
System.out.println(file.getPath());//获取文件的相对路径
System.out.println(file.getParent());//获取文件的父路径
System.out.println(file.canRead());//文件是否可读
System.out.println(file.canWrite());//文件是否可写
System.out.println(file.length());//文件的长度
System.out.println(file.lastModified());//文件最后一次修改的时间
System.out.println(file.isDirectory());//判断文件是否是一个目录
System.out.println(file.isHidden());//文件是否隐藏
System.out.println(file.isFile());//判断文件是否存在
  public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
  public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
list()获取某个目录下所有的文件或者文件夹:
1 package com.
3 import java.io.F
5 public class FileTest {
public static void main(String[] args){
File file=new File("D:/");//指定文件目录
String[] str=file.list();//获取指定目录下的所有文件或者文件夹的名称数组
for(String s : str){//加强for循环遍历输出
System.out.println(s);
1 package com.
3 import java.io.F
5 public class FileTest {
public static void main(String[] args){
File file=new File("D:/");//指定文件路径
File[] f=file.listFiles();//获取指定目录下的所有文件或者文件夹的File数组
for(File fi : f){//加强for循环遍历输出
System.out.println(fi);
案例演示:
获取某种格式的文件比如获取某种后缀的图片,并输出文件名:
1 package com.
3 import java.io.F
5 public class FileTest {
public static void main(String[] args){
File file=new File("C:\\Users\\biehongli\\Pictures\\xuniji");
String[] str=file.list();
for(String s : str){
if(s.endsWith(".jpg") || s.endsWith(".png")){//如果后缀是这种格式的就输出
System.out.println(s);
下面演示获取文件夹下面子目录里面的文件获取(并没有完全获取子目录的子目录等等,仅仅获取了子一级目录):
1 package com.
3 import java.io.F
5 public class FileTest {
public static void main(String[] args){
File file=new File("C:\\Users\\biehongli\\Pictures\\Camera Roll");
File[] f=file.listFiles();
for(File fi : f){
if(fi.isDirectory()){//判断如果是一个目录
String[] s=fi.list();
for(String str : s){
if(str.endsWith(".jpg")){
System.out.println(str);
A:文件名称过滤器的概述
    public String[] list(FilenameFilter filter)
    public File[] listFiles(FileFilter filter)
1 package com.
3 import java.io.F
4 import java.io.FilenameF
6 public class FileTest {
public static void main(String[] args){
File file=new File("C:\\Users\\biehongli\\Pictures\\Camera Roll");
String[] str=file.list(new FilenameFilter() {//过滤器,匿名内部类
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
//System.out.println(dir);//获取文件的路径
//System.out.println(name);//获取文件的名字
File f=new File(dir,name);
return f.isFile() && f.getName().endsWith(".jpg");
for(String s : str){
System.out.println(s);
7:下面以一些字节输入输出流具体的案例操作(操作的时候认清自己使用的是字节流还是字符流):
注意:read()方法读取的是一个字节,为什么返回是int,而不是byte
字节输入流可以操作任意类型的文件,比如图片音频等,这些文件底层都是以二进制形式的存储的,如果每次读取都返回byte,有可能在读到中间的时候遇到;那么这是byte类型的-1,我们的程序是遇到-1就会停止不读了,后面的数据就读不到了,所以在读取的时候用int类型接收,如果会在其前面补上;24个0凑足4个字节,那么byte类型的-1就变成int类型的255了这样可以保证整个数据读完,而结束标记的-1就是int类型
FileInputStream的单个字节读取:
FileOutputStream的单个字节写入:
1 package com.
3 import java.io.FileInputS
4 import java.io.FileOutputS
6 public class FileTest {
public static void main(String[] args) throws Exception{
FileInputStream fis=new FileInputStream("aaa.txt");
FileOutputStream fos=new FileOutputStream("bbb.txt",true);
//FileOutputStream()后面加true指文件后面可追加
int a=fis.read();//read()一次读取一个字节
System.out.println(a);//读取的一个字节输出
fos.write(101);//write()一次写一个字节
fis.close();//一定记得关闭流,养成好习惯
fos.close();
FileInputStream和FileOutputStream进行拷贝文本或者图片或者歌曲:
1 package com.
3 import java.io.FileInputS
4 import java.io.FileOutputS
6 public class FileTest {
public static void main(String[] args) throws Exception{
FileInputStream fis=new FileInputStream("aaa.txt");
FileOutputStream fos=new FileOutputStream("bbb.txt");
//如果没有bbb.txt,会创建出一个
while((b=fis.read())!=-1){
fos.write(b);
fis.close();
fos.close();
FileInputStream和FileOutputStream定义小数组进行读写操作:
1 package com.
3 import java.io.FileInputS
4 import java.io.FileOutputS
6 public class FileTest {
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream("aaa.txt");
FileOutputStream fos = new FileOutputStream("bbb.txt");
byte[] arr = new byte[1024 * 8];//自定义字节数组
while((len = fis.read(arr)) != -1) {
//fos.write(arr);
fos.write(arr, 0, len);//写出字节数组写出有效个字节个数
//IO流(定义小数组)
//write(byte[] b)
//write(byte[] b, int off, int len)写出有效的字节个数
fis.close();
fos.close();
&IO流(BufferedInputStream和BufferOutputStream拷贝)
* A:缓冲思想
  * 字节流一次读写一个数组的速度明显比一次读写一个字节的速度快很多,
  * 这是加入了数组这样的缓冲区效果,java本身在设计的时候,
  * 也考虑到了这样的设计思想,所以提供了字节缓冲区流
* B.BufferedInputStream
  * BufferedInputStream内置了一个缓冲区(数组)
  * 从BufferedInputStream中读取一个字节时
  * BufferedInputStream会一次性从文件中读取8192个, 存在缓冲区中, 返回给程序一个
  * 程序再次读取时, 就不用找文件了, 直接从缓冲区中获取
  * 直到缓冲区中所有的都被使用过, 才重新从文件中读取8192个
* C.BufferedOutputStream
  * BufferedOutputStream也内置了一个缓冲区(数组)
  * 程序向流中写出字节时, 不会直接写到文件, 先写到缓冲区中
  * 直到缓冲区写满, BufferedOutputStream才会把缓冲区中的数据一次性写到文件里
1 package com.
3 import java.io.BufferedInputS
4 import java.io.BufferedOutputS
5 import java.io.FileInputS
6 import java.io.FileOutputS
8 public class FileTest {
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream("aaa.txt");
FileOutputStream fos = new FileOutputStream("bbb.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
//使用装饰模式,把fis装饰进去bis中。使用缓冲读取速度变快
BufferedOutputStream bos=new BufferedOutputStream(fos);
while((b=bis.read())!=-1){
bos.write(b);
bis.close();
bos.close();
&面试题:小数组的读写和带Buffered的读取哪个更快?
  * 定义小数组如果是8192个字节大小和Buffered比较的话
  * 定义小数组会略胜一筹,因为读和写操作的是同一个数组
  * 而Buffered操作的是两个数组
IO流(flush和close方法的区别)
flush()方法: 用来刷新缓冲区的,刷新后可以再次写出(字节缓冲流内置缓冲区,如果没有读取出来,可以使用flush()刷新来)
close()方法:用来关闭流释放资源的的,如果是带缓冲区的流对象的close()方法,不但会关闭流,还会再关闭流之前刷新缓冲区,关闭后不能再写出
8:字符流FileReader和FileWriter
字符流是什么
  * 字符流是可以直接读写字符的IO流
  * 字符流读取字符, 就要先读取到字节数据, 然后转为字符. 如果要写出字符, 需要把字符转为字节再写出.    
IO流(什么情况下使用字符流)
* 字符流也可以拷贝文本文件, 但不推荐使用. 因为读取时会把字节转为字符, 写出时还要把字符转回字节.
* 程序需要读取一段文本, 或者需要写出一段文本的时候可以使用字符流
* 读取的时候是按照字符的大小读取的,不会出现半个中文
* 写出的时候可以直接将字符串写出,不用转换为字节数组
IO流(字符流是否可以拷贝非纯文本的文件)
* 不可以拷贝非纯文本的文件
* 因为在读的时候会将字节转换为字符,在转换过程中,可能找不到对应的字符,就会用?代替,写出的时候会将字符转换成字节写出去
* 如果是?,直接写出,这样写出之后的文件就乱了,看不了了
1 package com.
3 import java.io.FileR
4 import java.io.FileW
6 public class FileTest {
public static void main(String[] args) throws Exception{
//FileReader类的read()方法可以按照字符大小读取
FileReader fr=new FileReader("aaa.txt");
while((b=fr.read())!=-1){
System.out.println((char)b);//int类型转为字符型
fr.close();
//FileWriter类的write()方法可以自动把字符转为字节写出
FileWriter fw = new FileWriter("aaa.txt",true);
fw.write("aaa");
fw.close();
//字符流的拷贝
FileReader fr2 = new FileReader("aaa.txt");
FileWriter fw2 = new FileWriter("bbb.txt");
while((ch = fr2.read()) != -1) {
fw2.write(ch);
fr2.close();
fw2.close();
1 package com.
3 import java.io.BufferedR
4 import java.io.BufferedW
5 import java.io.FileR
6 import java.io.FileW
8 public class FileTest {
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new FileReader("aaa.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("bbb.txt"));
//BufferedReader和BufferedWriter的使用:
while((b=br.read())!=-1){
bw.write((char)b);
br.close();
bw.close();
&先写到这里吧,内容比较多,以后有时间再总结,也方便自己脑补                                         
阅读(...) 评论()Java输入输出流总结
  流是数据源或数据目标的输入或输出设备的抽象表示。支持流输入和输出的主要包是java.io,但是也有其他的包,比如java.nio.file。java.io包支持两种类型的流——包含二进制数据的字节流和包含字符数据的字符流。
  当写数据到字节流中时,数据会以字节序列的形式写到流中,与它们在内存中的形式完全一样,在这个过程中不会发生数据转换。即java.io包中的InputStream和OutputStream的派生类,通常用来读取二进制数据,如图像和声音。
  将字符串作为字符数据读入流时,默认Unicode字符会首先被自动转化成主机的本地字符表示,之后再写到流中。包括Reader和Writer类。字符流用于存储和提取文本,也可以使用字符流读取由非java程序创建的文本文件。
  但是,Read和Write并不是取代InputStream和OutputStream,有时,你还必须同时使用"基于byte的类"和"基于字符的类"。为此,它还提供了两个"适配器(adapter)"类。InputStreamReader负责将InputStream转化成Reader,而OutputStreamWriter则将OutputStream转化成Writer。
二、字节流
  包java.io中的两个类InputStream和OutputStream,java基于他们对流I/O操作提供支持。InputStream和OutputStream都是抽象类,无法创建实例,但是可以用于派生具有更加实际输入输出功能的类。这两个类都实现了Closeable接口,而Closeable接口只声明了方法close()——关闭流并且释放流对象保存的所有资源。
  1、InputStream类
  InputStream包含三个read()方法用于从流中读取数据:
  public&abstract int&read();  抽象方法,以int类型返回流中可用的下一个字节。读取到末尾,返回-1。
  public&int read(byte[] array);  该方法从流中读取字节填充到数组array的连续元素中,最大读取长度为array.length个字节。读取到末尾,返回-1。
  public&int read(byte[] array, int offset, int length);  该方法从流中读取length长度的字节填充到数组array中,将array[offset]作为存放起始位置。读取到末尾,返回-1。
  public int available();  返回输入流中可以读取的字节数。注意:若输入阻塞,当前线程将被挂起,如果InputStream对象调用这个方法的话,它只会返回0,这个方法必须由继承InputStream类的子类对象调用才有用。
  public long skip(long n);  忽略输入流中的n个字节,返回值是实际忽略的字节数, 跳过一些字节再读取。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  InputStream类的派生类结构:
 2、OutputStream类
  OutputStream提供了3个write()方法来输出数据,和InputStream相对应:
  public abstract void write(int b);  先将int转换成byte类型,把低字节写入到输出流中。
  public void write(byte[] array);  将数组array中的字节写到输出流。
  public void write(byte[] array, int offset, int length);  将数组array中从array[offset]开始的length个字节写到输出流。
  public void flush();  将数据缓冲区中数据全部输出,并清空缓冲区。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  OutputStream类的派生类结构:
 3、FileInputStream类
  FileInputStream类是InputStream类的子类,用来处理以文件作为数据输入源的数据流。
  使用方法:  
  方式1:
  File fin=new File("d:/abc.txt");
  FileInputStream in=new FileInputStream(fin);
  方式2:
  FileInputStream in=new&FileInputStream("d: /abc.txt");
  方式3:
  构造函数将 FileDescriptor()对象作为其参数。
  FileDescriptor() fd=new FileDescriptor();
  FileInputStream f2=new FileInputStream(fd);
  如果发生I/O类型错误,会抛出IOException类型的异常。
  4、FileOutputStream类
  FileOutputStream类用来处理以文件作为数据输出目的数据流;一个表示文件名的字符串,也可以是File或FileDescriptor对象。
  创建一个文件流对象方法:
  方式1:
  File f=new File("d:/abc.txt");
  FileOutputStream out=new FileOutputStream (f);
  方式2:
  FileOutputStream out=new
  FileOutputStream("d:/abc.txt");
  方式3:构造函数将 FileDescriptor()对象作为其参数。
  FileDescriptor() fd=new FileDescriptor();
  FileOutputStream f2=new FileOutputStream(fd);
  方式4:构造函数将文件名作为其第一参数,将布尔值作为第二参数。
  FileOutputStream f=new FileOutputStream("d:/abc.txt",true);
  如果发生I/O类型错误,会抛出IOException类型的异常。
使用过程:
  (1)生成文件流对象(对文件读操作时应该为FileInputStream类,而文件写应该为FileOutputStream类);
  (2)调用FileInputStream或FileOutputStream类中的功能函数如read()、write(int b)等)读写文件内容;
  (3)关闭文件close()。
  (1)文件中写数据时,若文件已经存在,则覆盖存在的文件;
  (2)的读/写操作结束时,应调用close方法关闭流。
例子:利用FileInputStream读取一个文件,并存入缓存中,然后通过FileOutputStream写到一个新的文件
import java.io.*;
3 public class FileStreamDemo {
public static void main(String[] args) throws IOException {
//创建两个文件,face.gif是已经存在文件,newFace.gif是新创建的文件
File inFile = new File("1.gif");
File outFile = new File("new1.gif");
<span style="color: # 10
//创建流文件读入与写出类
<span style="color: # 11
FileInputStream inStream = new FileInputStream(inFile);
<span style="color: # 12
FileOutputStream outStream = new FileOutputStream(outFile);
<span style="color: # 13
<span style="color: # 14
//通过available方法取得流的最大字符数
<span style="color: # 15
byte[] b = new byte[inStream.available()];
<span style="color: # 16
inStream.read(b);
//读入流,保存在byte数组
<span style="color: # 17
outStream.write(b);
//写出流,保存在文件newFace.gif中
<span style="color: # 18
<span style="color: # 19
inStream.close();
<span style="color: # 20
outStream.close();
<span style="color: # 21
<span style="color: # 22 }
 5、File类
  File类与InputStream / OutputStream类同属于一个包,它不允许访问文件内容。
  File类主要用于命名文件、查询文件属性和处理文件目录。
  6、从一个流构造另一个流
  java的流类提供了结构化方法,如,底层流和高层过滤流。而高层流不是从输入设备读取,而是从其他流读取。同样高层输出流也不是写入输出设备,而是写入其他流。
  使用"分层对象(layered objects)",为单个对象动态地,透明地添加功能的做法,被称为Decorator Pattern。Decorator模式要求所有包覆在原始对象之外的对象,都必须具有与之完全相同的接口。这使得decorator的用法变得非常的透明--无论对象是否被decorate过,传给它的消息总是相同的。这也是Java I/O类库要有"filter(过滤器)"类的原因:抽象的"filter"类是所有decorator的基类。Decorator模式常用于如下的情形:如果用继承来解决各种需求的话,类的数量会多到不切实际的地步。Java的I/O类库需要提供很多功能的组合,于是decorator模式就有了用武之地。
  为InputStream和OutputStream定义decorator类接口的类,分别是FilterInputStream和FilterOutputStream。
  FilterInputStream的种类:
    DataInputStream:与DataOutputStream配合使用,这样你就能以一种"可携带的方式(portable fashion)"从流里读取primitives了(int,char,long等)
    BufferedInputStream:用这个类来解决"每次要用数据的时候都要进行物理读取"的问题。意思是"用缓冲区"。
    LineNumberInputStream:跟踪输入流的行号;有getLineNumber( )和setLineNumber(int)方法
    PushbackInputStream:有一个"弹压单字节"的缓冲区(has a one byte push-back buffer),这样你就能把最后读到的那个字节再压回去了。
  FilterOutputStream的种类:
    DataOutputStream:与DataInputStream配合使用,这样你就可以用一种"可携带的方式(portable fashion)"往流里写primitive了(int, char, long,等)
    PrintStream:负责生成带格式的输出(formatted output)。DataOutputStrem负责数据的存储,而PrintStream负责数据的显示。
    BufferedOutputStream:用 这个类解决"每次往流里写数据,都要进行物理操作"的问题。也就是说"用缓冲区"。用flush( )清空缓冲区。
  7、BufferedInputStream类  
  BufferedInputStream与BufferedOutputStream可以为InputStream、OutputStream类的对象增加缓冲区功能。构建BufferedInputStream实例时,需要给定一个InputStream类型的实例,实现BufferedInputStream时,实际上最后是实现InputStream实例。同样地,在构建BufferedOutputStream时,也需要给定一个OutputStream实例,实现BufferedOutputStream时,实际上最后是实现OutputStream实例。
  BufferedInputStream的数据成员buf是一个位数组,默认为2048字节。当读取数据来源时,例如文件,BufferedInputStream会尽量将buf填满。当使用read()方法时,实际上是先读取buf中的数据,而不是直接对数据来源作读取。当buf中的数据不足时,BufferedInputStream才会再实现给定的InputStream对象的read()方法,从指定的装置中提取数据。
  方式1:
  File srcFile = new File(args[0]);
  BufferedInputStream bufferedInputStream =&new BufferedInputStream(new FileInputStream(srcFile));
  创建&BufferedInputStream&并保存其参数,即输入流&in,以便将来使用。创建一个内部缓冲区数组并将其存储在&buf&中。
  方式2:
  File srcFile = new File(args[0]);
  BufferedInputStream bufferedInputStream =&new BufferedInputStream(new FileInputStream(srcFile),1024);
  创建具有指定缓冲区大小的&BufferedInputStream,并保存其参数,即输入流&in,以便将来使用。创建一个长度为&size&的内部缓冲区数组并将其存储在&buf&中。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  8、BufferedOutputStream类
  BufferedOutputStream的数据成员buf是一个位数组,默认为512字节。当使用write()方法写入数据时,实际上会先将数据写至buf中,当buf已满时才会实现给定的OutputStream对象的write()方法,将buf数据写至目的地,而不是每次都对目的地作写入的动作。
  方式1:
  File desFile = new File(args[1]);
  BufferedOutputStream bufferedOutputStream =&new BufferedOutputStream(new FileOutputStream(desFile));
  创建一个新的缓冲输出流,以将数据写入指定的基础输出流。
  方式2:
  File desFile = new File(args[1]);
  BufferedOutputStream bufferedOutputStream =&new BufferedOutputStream(new FileOutputStream(desFile),1024);
  创建一个新的缓冲输出流,以将具有指定缓冲区大小的数据写入指定的基础输出流。
  如果发生I/O类型错误,会抛出IOException类型的异常。
例子:使用BufferedInputStream和BufferedOutputStream复制BuffferedStreamDemo.java的内容至BufferedStreamDemo.txt文件并显示输出
1 import java.io.*;
3 public class BufferedStreamDemo {
public static void main(String[] args){
byte[] data=new byte[1];
File srcFile=new File("BufferedStreamDemo.java");
<span style="color: # 10
File desFile=new File("BufferedStreamDemo.txt");//声明两个文件实例
<span style="color: # 11
<span style="color: # 12
BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(srcFile));//实例化BufferedInputStream
<span style="color: # 13
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(desFile));//实例化BufferedOutputStream
<span style="color: # 14
<span style="color: # 15
System.out.println("复制文件: "+srcFile.length()+"字节");
<span style="color: # 16
//将从BufferedStreamDemo.java文件读取的字节写到data,然后再写到BufferedStreamDemo.txt
<span style="color: # 17
while(bufferedInputStream.read(data)!=-1){
<span style="color: # 18
bufferedOutputStream.write(data);
<span style="color: # 19
<span style="color: # 20
<span style="color: # 21
//将缓冲区中的数据全部写出
<span style="color: # 22
bufferedOutputStream.flush();
<span style="color: # 23
<span style="color: # 24
System.out.println("复制完成");
<span style="color: # 25
<span style="color: # 26
//显示输出BufferedStreamDemo.txt文件的内容
<span style="color: # 27
bufferedInputStream =new BufferedInputStream(new FileInputStream(new File("BufferedStreamDemo.txt")));
<span style="color: # 28
while(bufferedInputStream.read(data)!=-1){
<span style="color: # 29
String str=new String(data);
<span style="color: # 30
System.out.print(str);
<span style="color: # 31
<span style="color: # 32
<span style="color: # 33
bufferedInputStream.close();
<span style="color: # 34
bufferedOutputStream.close();
<span style="color: # 35
<span style="color: # 36
}catch(ArrayIndexOutOfBoundsException e){
<span style="color: # 37
System.out.println("using: java useFileStream src des");
<span style="color: # 38
e.printStackTrace();
<span style="color: # 39
}catch(IOException e){
<span style="color: # 40
e.printStackTrace();
<span style="color: # 41
<span style="color: # 42
<span style="color: # 43 }
 9、DataInputStream类
  DataInputStream和DataOutputStream可提供一些对Java基本数据类型写入的方法,像读写int、double和boolean等的方法。由于Java的数据类型大小是规定好的,在写入或读出这些基本数据类型时,就不用担心不同平台间数据大小不同的问题。
  有时没有必要存储整个对象的信息,而只是要存储一个对象的成员数据,成员数据的类型假设都是Java的基本数据类型,这样的需求不必使用到与Object输入、输出相关的流对象,可以使用DataInputStream、DataOutputStream来写入或读出数据。
  DataInputStream&dataInputStream&=&new&DataInputStream(new&FileInputStream(args[0]));&
  方法:
  public&String readUTF();  读入一个已使用UTF-8修改版格式编码的字符串
  public&String readLine();  是通过BufferedReader.readLine()实现的。
  public&boolean&readB  
  public&int&readInt();  
  public&byte readByte();  
  public char readChar();  等等一系列读取基本数据类型的方法
  如果发生I/O类型错误,会抛出IOException类型的异常。
  10、DataOutputStream类
  DataOutputStream&dataOutputStream&=&new&DataOutputStream(new&FileOutputStream(args[0]));
  方法:  
  public&void writeBoolean(boolean b);  将一个boolean值以1-byte形式写入基本输出流。
  public&void writeByte(int v);  将一个byte值以1-byte值形式写入到基本输出流中。
  public&void writeBytes(String s);  将字符串按字节顺序写入到基本输出流中。
  public&void writeChar(int v);  将一个char值以2-byte形式写入到基本输出流中。先写入高字节。
  public&void writeInt(int v);  将一个int值以4-byte值形式写入到输出流中先写高字节。
  public&void writeUTF(String str);  以机器无关的的方式用UTF-8修改版将一个字符串写到基本输出流。该方法先用writeShort写入两个字节表示后面的字节数。
  public&int size();  返回written的当前值。
  如果发生I/O类型错误,会抛出IOException类型的异常。
例子:先用DataOutputStream想文本写入各种类型数据,再用DataInputStream从中读取各种类型数据。
1 import java.io.*;
3 public class DataInputStreamDemo {
private static final int LEN = 5;
public static void main(String[] args) {
// 测试DataOutputStream,将数据写入到输出流中。
testDataOutputStream() ;
<span style="color: # 10
// 测试DataInputStream,从上面的输出流结果中读取数据。
<span style="color: # 11
testDataInputStream() ;
<span style="color: # 12
<span style="color: # 13
<span style="color: # 14
<span style="color: # <span style="color: #
* DataOutputStream的API测试函数
<span style="color: # <span style="color: #
<span style="color: # 17
private static void testDataOutputStream() {
<span style="color: # 18
<span style="color: # 19
<span style="color: # 20
File file = new File("file.txt");
<span style="color: # 21
DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
<span style="color: # 22
<span style="color: # 23
out.writeBoolean(true);
<span style="color: # 24
out.writeByte((byte)0x41);
<span style="color: # 25
out.writeChar((char)0x4243);
<span style="color: # 26
out.writeShort((short)0x4445);
<span style="color: # 27
out.writeInt(0x);
<span style="color: # 28
out.writeLong(0x0FEDCBAL);
<span style="color: # 29
out.writeUTF("abcdefghijklmnopqrstuvwxyz严12");
<span style="color: # 30
<span style="color: # 31
out.close();
<span style="color: # 32
} catch (FileNotFoundException e) {
<span style="color: # 33
e.printStackTrace();
<span style="color: # 34
catch (IOException e) {
<span style="color: # 35
e.printStackTrace();
<span style="color: # 36
<span style="color: # 37
<span style="color: # 38
<span style="color: # <span style="color: #
* DataInputStream的API测试函数
<span style="color: # <span style="color: #
<span style="color: # 41
private static void testDataInputStream() {
<span style="color: # 42
<span style="color: # 43
<span style="color: # 44
File file = new File("file.txt");
<span style="color: # 45
DataInputStream in =
<span style="color: # 46
new DataInputStream(
<span style="color: # 47
new FileInputStream(file));
<span style="color: # 48
<span style="color: # 49
System.out.printf("byteToHexString(0x8F):0x%s\n", byteToHexString((byte)0x8F));
<span style="color: # 50
System.out.printf("charToHexString(0x8FCF):0x%s\n", charToHexString((char)0x8FCF));
<span style="color: # 51
System.out.printf("readBoolean():%s\n", in.readBoolean());
<span style="color: # 52
System.out.printf("readByte():0x%s\n", byteToHexString(in.readByte()));
<span style="color: # 53
System.out.printf("readChar():0x%s\n", charToHexString(in.readChar()));
<span style="color: # 54
System.out.printf("readShort():0x%s\n", shortToHexString(in.readShort()));
<span style="color: # 55
System.out.printf("readInt():0x%s\n", Integer.toHexString(in.readInt()));
<span style="color: # 56
System.out.printf("readLong():0x%s\n", Long.toHexString(in.readLong()));
<span style="color: # 57
System.out.printf("readUTF():%s\n", in.readUTF());
<span style="color: # 58
<span style="color: # 59
in.close();
<span style="color: # 60
} catch (FileNotFoundException e) {
<span style="color: # 61
e.printStackTrace();
<span style="color: # 62
catch (IOException e) {
<span style="color: # 63
e.printStackTrace();
<span style="color: # 64
<span style="color: # 65
<span style="color: # 66
<span style="color: # 67
// 打印byte对应的16进制的字符串
<span style="color: # 68
private static String byteToHexString(byte val) {
<span style="color: # 69
return Integer.toHexString(val & 0xff);
<span style="color: # 70
<span style="color: # 71
<span style="color: # 72
// 打印char对应的16进制的字符串
<span style="color: # 73
private static String charToHexString(char val) {
<span style="color: # 74
return Integer.toHexString(val);
<span style="color: # 75
<span style="color: # 76
<span style="color: # 77
// 打印short对应的16进制的字符串
<span style="color: # 78
private static String shortToHexString(short val) {
<span style="color: # 79
return Integer.toHexString(val & 0xffff);
<span style="color: # 80
<span style="color: # 81 }
三、字符流
  包java.io中的两个类Reader和Writer,他们是能将字节流以字符流方式进行读写的对象,因此字符流在本质上是以Reader和Writer封装的字节流。Reader和Writer都是抽象类,这两个类都实现了声明close()方法的AutoCloseable接口。
  Reader和Writer类以及他们的子类本身都不是流,但是他们提供了一些方法,可用于将底层的流作为字符流读写。因此,通常使用底层的InputStream和OutputStream对象来创建Reader和Writer对象。
  1、Reader类
  还实现了Readable接口,该接口声明了read()方法,用于将字符读入作为参数传入read()方法的CharBuffer对象。
  public int read();  读取单个字符。
  public int read(char[] cbuf);  读取多个字符到字符数组cbuf。
  public abstract int read(char[] cbuf,int off,int len);  读取len个字符到字符数组cbuf中,从cbuf[off]开始存放。
  public boolean ready();  这个输入流是否准备好了。
  public void &reset();  重置输入流。
  public long skip(long n);  跳过n个字符读取。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  Reader类的派生类结构:
2、Writer类
  Writer类实现了Appendable接口,声明了3种版本的append()方法,还有5个write()方法。
  public Writer append(char c);  将字符c附加到Writer封装的任意流后面。
  public Writer append(CharSequence csq);  将CharSequence类型的参数附加到底层流的后面。
  public Writer append(CharSequence csq, int start, int end);  将一个字符序列的子序列附加到底层流的后面。
  public void write(int c);  写一个单独的字符。
  public void write(String str);  写一个字符串。
  public void write(String str, int off, int len);  写一个字符串的子串。
  public void write(char[] cbuf);  写一个字符数组。
  public abstract void write(char[] cbuf, int off, int len);  写一个字符数组的子串。
  public abstract&void flush();  将数据缓冲区中数据全部输出,并清空缓冲区。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  Writer类的派生类结构:
 3、InputStreamReader类
  若想对InputStream和OutputStream进行字符处理,可以使用InputStreamReader和OutputStreamWriter为其加上字符处理的功能,它们分别为Reader和Writer的子类。
  举个例子来说,若想要显示纯文本文件的内容,不用费心地自行判断字符编码(例如范例14.15中要费心地自行判断是ASCII英文字母或BIG5中文字),只要将InputStream、OutputStream的实例作为构建InputStreamReader、OutputStreamWriter时的变量,就可以操作InputStreamReader和OutputStreamWriter来进行文本文件的读取,让它们为您做字符判断与转换的动作。
  如果以文件操作为例,则内存中的字符数据需要通过OutputStreamWriter变为字节流才能保存在文件中,读取时需要将读入的字节流通过InputStreamReader变为字符流。过程如下:  写入数据--&内存中的字符数据--&字符流--&OutputStreamWriter--&字节流--&网络传输(或文件保存)  读取数据&--内存中的字符数据&--字符流&--InputStreamReader&--字节流&--网络传输(或文件保存)
  构造方法:
  public InputStreamReader(InputStream in);  创建一个使用默认字符集的 InputStreamReader。
  public InputStreamReader(InputStream in, String charsetName);  创建使用指定字符集的 InputStreamReader。
  public InputStreamReader(InputStream in, Charset cs);  创建使用指定字符集的 InputStreamReader。
  public InputStreamReader(InputStream in, CharsetDecoder dec);  创建使用指定字符集解码器的 InputStreamReader。
  常用Charset:
7 位 ASCII 字符,也叫作&ISO646-US、Unicode 字符集的基本拉丁块
ISO-8859-1&&
ISO 拉丁字母表 No.1,也叫作&ISO-LATIN-1
8 位 UCS 转换格式
16 位 UCS 转换格式,Big Endian(最低地址存放高位字节)字节顺序
16 位 UCS 转换格式,Little-endian(最高地址存放低位字节)字节顺序
16 位 UCS 转换格式,字节顺序由可选的字节顺序标记来标识
 常用方法:  public String getEncoding();  返回此流使用的字符编码的名称。如果该编码有历史上用过的名称,则返回该名称;否则返回该编码的规范化名称。  
  如果发生I/O类型错误,会抛出IOException类型的异常。
  4、OutputStreamWriter类
  构造方法:
  public&OutputStreamWriter(OutputStream out);  创建使用默认字符编码的 OutputStreamWriter。
  public&OutputStreamWriter(OutputStream out, String charsetName);  创建使用给定字符集的 OutputStreamWriter。
  public&OutputStreamWriter(OutputStream out, Charset cs);  创建使用给定字符集的 OutputStreamWriter。
  public&OutputStreamWriter(OutputStream out, CharsetEncoder enc);  创建使用给定字符集编码器的 OutputStreamWriter。
  常用方法:  public String getEncoding();  返回此流使用的字符编码的名称。如果该编码具有历史名称,则返回该名称;否则返回该编码的规范化名称。
  如果发生I/O类型错误,会抛出IOException类型的异常。
例子:从一个文件中用InputStreamReader读取,然后将字节流转换成字符流存在字符串数组;用OutputStreamWriter向另一个文件写入该数组。
1 1 import java.io.*;
3 public class InputStreamReaderDemo {
public static void main(String[] args) throws Exception { // 所有的异常抛出
File f1 = new File("helpinfo.txt");
File f2 = new File("test.txt");
Writer out = null;
Reader in = null;
out = new OutputStreamWriter(new FileOutputStream(f2));// 通过子类实例化父类对象,字节流变为字符流
<span style="color: # 10
in = new InputStreamReader(new FileInputStream(f1));
<span style="color: # 11
char c[] = new char[1024];
<span style="color: # 12
in.read(c);
<span style="color: # 13
System.out.print(c);
<span style="color: # 14
out.write(c);
// 使用字符流输出
<span style="color: # 15
in.close();
<span style="color: # 16
out.close();
<span style="color: # 17
<span style="color: # 18 }
 5、FileReader类
  FileReader类创建了一个可以读取字符流文件内容的Reader类。
  构造方法:
  public FileReader(File file);  在给定从中读取数据的&File&的情况下创建一个新&FileReader。
  public FileReader(String fileName);  在给定从中读取数据的文件名的情况下创建一个新&FileReader。
  public FileReader(FileDescripter fd);  在给定从中读取数据的&FileDescriptor&的情况下创建一个新&FileReader。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  6、FileWriter类
  FileWriter类创建一个可以用字符流写文件的Writer类。
  构造方法:
  public FileWriter(File file);  在给出 File 对象的情况下构造一个FileWriter对象。
  public FileWriter(File file, boolean append);  在给出File对象的情况下构造一个FileWriter对象,如果第二个参数为true,则将字节写入文件末尾处,而不是写入文件开始处。
  public FileWriter(FileDescripter fd);  构造与某个文件描述符相关联的FileWriter对象。
  public FileWriter(String fileName);  在给出文件名的情况下构造一个FileWriter对象。
  public FileWriter(String fileName, boolean append);  在给出文件名的情况下构造 FileWriter 对象,如果第二个参数为true,则将字节写入文件末尾处,而不是写入文件开始处。
  如果发生I/O类型错误,会抛出IOException类型的异常。
例子:从一个文本中读取字符存在数组中,然后再再到另一个文本。
1 1 import java.io.*;
3 public class FileReaderDemo {
public static void main (String args[ ] ) throws Exception {
FileReader fr = new FileReader("helpinfo.txt");
FileWriter fw = new FileWriter("test.txt");
char data[]=new char[1024];
int num = fr.read(data);
System.out.println(num);
<span style="color: # 10
fw.write(data);
<span style="color: # 11
fr.close();
<span style="color: # 12
fw.close();
<span style="color: # 13
<span style="color: # 14 }
7、BufferedReader类 
  从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。通常,Reader 所作的每个读取请求都会导致对基础字符或字节流进行相应的读取请求。因此,建议用 BufferedReader 包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和 InputStreamReader)。例如:BufferedReader in = new BufferedReader(new InputStream(System.in));
  构造函数:
  public BufferedReader(Reader in);  创建一个使用默认大小输入缓冲区的缓冲字符输入流。
  public BufferedReader(Reader in, int size);  创建一个使用指定大小输入缓冲区的缓冲字符输入流。
  常用方法:
  public String readline();  读取一个文本行,通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。
  如果发生I/O类型错误,会抛出IOException类型的异常。
  8、BufferedWriter类
  将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。可以指定缓冲区的大小,或者接受默认的大小。在大多数情况下,默认值就足够大了。该类提供了newLine() 方法,它使用平台自己的行分隔符概念,此概念由系统属性line.separetor定义。并非所有平台都使用新行符 ('\n') 来终止各行。因此调用此方法来终止每个输出行要优于直接写入新行符。通常 Writer 将其输出立即发送到基础字符或字节流。除非要求提示输出,否则建议用 BufferedWriter 包装所有其 write() 操作可能开销很高的 Writer(如 FileWriters 和 OutputStreamWriters)。例如,BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
  构造方法:
  public BufferedWriter(Writer out);  创建一个使用默认大小输出缓冲区的缓冲字符输出流。
  public BufferedWriter(Writer out, int size);  创建一个使用指定大小输出缓冲区的新缓冲字符输出流。
  常用方法:
  public void newline();  写入一个行分隔符。行分隔符字符串由系统属性line.separetor定义,并且不一定是单个新行 ('\n') 符。
  如果发生I/O类型错误,会抛出IOException类型的异常。
例子:从一个文本中读取字符存在数组中,然后再到另一个文本。
import java.io.*;
3 public class BufferedReaderDemo {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String b = null;
File file = new File("abc.txt");
if (!file.exists() != false) {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
bw = new BufferedWriter(new FileWriter(file));
FileReader fr = new FileReader("helpinfo.txt");
br = new BufferedReader(fr);
while ((b = br.readLine()) != null) {
System.out.println(b);
bw.write(b); //输出字符串
bw.newLine();//换行
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
br.close();
//bw.close();
} catch (IOException e) {
e.printStackTrace();
阅读(...) 评论()}

我要回帖

更多关于 输入输出流 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信