JVAV-IO-——字节流

5 篇文章 1 订阅
4 篇文章 0 订阅

JAVA IO——字节流

1.IO流

什么是io流呢?

简单说,就是在java中把不同的输入/输出源(键盘,文件等)抽象表述为“流”(stream),通过流的方式允许Java程序使用相同的方式来访问不同的输入输出源。

在java中所有流类型都放在java.io包中。

2.流的分类

  • 输入流和输出流
  • 字节流和字符流
  • 节点流和处理流

3.InputStream

InputStream是所有输入字节流的抽象类

它的主要方法如下

修饰符和类型方法描述
voidclose()关闭此输入流并释放与该流关联的所有系统资源。
abstract intread()从输入流中读取下一个数据字节。
intread(byte[] b)从输入流中读取一些字节数并将它们存储到缓冲区数组中b
intread(byte[] b, int off, int len)len将输入流中的数据字节读取到一个字节数组中。
byte[]readAllBytes()从输入流中读取所有剩余字节。

4.OutputStream

OutputStream是所有输出字节流的抽象类

5.主要方法如下:

修饰符和类型方法描述
voidclose()关闭此输出流并释放与该流关联的所有系统资源。
voidwrite(byte[] b)b.length指定字节数组中的字节写入此输出流。
voidwrite(byte[] b, int off, int len)len将从offset开始的指定字节数组中的字节写入off此输出流。
abstract voidwrite(int b)将指定的字节写入此输出流。
voidflush()刷新此输出流并强制写出任何缓冲的输出字节。

5.FileInputStream/FileOutputStream类

FileInputStream/FileOutputStream类是实现了InputStream/OutputStream的实现类。

FileInputStream类,具体实现了在文件上读取数据。

FileOutputStream类,实现了向文件中写入byte数据。

FilenputStream的常用方法
  • 构造函数:

    构造函数描述
    FileInputStream(File file)FileInputStream通过打开与实际文件的连接来创建一个实际文件,该文件由文件系统中的File 对象命名file
    FileInputStream(String name)FileInputStream通过打开与实际文件的连接来创建一个实际文件,该文件由name 文件系统中的路径名命名。
  • close()

  • read()

  • read(byte[] b)

  • read(byte[] b,int off ,int length)

    它们的用法与InputStream抽象类中定义的用法相同,这里就不赘述。

FileOutputStream的常用方法
  • 构造函数:

    构造函数描述
    FileOutputStream(File file)创建文件输出流以写入由指定File对象表示的文件。
    FileOutputStream(File file, boolean append)创建文件输出流以写入由指定File对象表示的文件。
    FileOutputStream(String name)创建文件输出流以写入具有指定名称的文件。
    FileOutputStream(String name, boolean append)

值得注意的是,在其构造函数中有append参数,它规定了是否以追加的形式往文件中录入数据。

  • close()

  • write()

  • write(byte[] b)

  • write(byte[] b, int off,int length)

  • flush()

    同样与OutputStream抽象类中定义的用法相同。

代码实例:
//复制文件

public static void copyFile(File srefile, File destfile) throws IOException {
		FileOutputStream out = new FileOutputStream(destfile);
		FileInputStream in = new FileInputStream(srefile);
		if (!srefile.exists()) {
			throw new IllegalArgumentException("不存在文件"+srefile.getName());
		}
		if (!srefile.isFile()) {
			throw new IllegalArgumentException(srefile.getName()+"不是文件");
		}
		byte[] buf = new byte[8*1024];
		int b ;
		while((b = in.read(buf, 0, buf.length))!=-1) {
			out.write(buf);
			out.flush();//最好加上,但是在带有缓冲区的输出流类一定要加
		}
		in.close();
		out.close();
	}


//将文件以16进制方式输出,并且文件不够大,可以一次存入字节数组buf中
public static void printFor(String file) throws IOException {
		FileInputStream in = new FileInputStream(file);
		byte[] buf = new byte[20*1024];
		int bytes = in.read(buf, 0, buf.length);
		int j = 1;
		for (int i = 0; i < bytes ;i++) {
			System.out.print(Integer.toHexString(buf[i] &0xff)+" ");
			if (j++ % 10 == 0) {
				System.out.println();
			}
		}
	}


//将文件以16进制方式输出,并且文件足够大,需要多次存入字节数组buf中
public static void printWhile(String file) throws IOException {
		FileInputStream in = new FileInputStream(file);
		byte[] buf = new byte[20*1024];
		int bytes;
		int j = 1;
		while((bytes = in.read(buf, 0, buf.length)) != -1)
		for (int i = 0; i < bytes ;i++) {
			System.out.print(Integer.toHexString(buf[i]&0xff)+" ");
			if (j++ % 10 == 0) {
				System.out.println();
			}
		}
		
	}
	/*
	 * 如何该文件不存在,则直接创建,如果存在,删除后创建
	 * 使用参数true,在存在的文件后追加;
	 */

6.DataOutputStream/DataInputStream类

DataOutputStream/DataInputStream类是对“流“功能的扩展,可以方便的读取int,long,char,String等类型数据。同样是继承了InputStreamheOutputStream。

DataInputStream的常用方法
  • 构造函数

    构造函数描述
    DataInputStream(InputStream in)创建使用指定的基础InputStream的DataInputStream。
  • 常用方法

    intread(byte[] b)从包含的输入流中读取一些字节数并将它们存储到缓冲区数组中b
    intread(byte[] b, int off, int len)len将包含的输入流中的最多数据字节读入字节数组。

    它还有readBoolean(), readByte(), readChar(), readDouble(), readFloat(), readInt(), readLong(), readShort(),readUTF() 等等方法。正如其方法名,大概就可以知道他们的用法。

DataOutputStream的常用方法
  • 构造函数

    构造函数描述
    DataOutputStream(OutputStream out)创建新数据输出流以将数据写入指定的基础输出流。
  • 常用方法

    voidflush()刷新此数据输出流。
    intsize()返回计数器的当前值,即written到目前为止写入此数据输出流的字节数。
    voidwrite(byte[] b, int off, int len)len将从offset开始的指定字节数组中的字节写入off基础输出流。
    voidwrite(int b)将指定的字节(参数的低八位 b)写入基础输出流。
    voidwriteBoolean(boolean v)将a boolean作为1字节值写入底层输出流。
    voidwriteByte(int v)将a byte作为1字节值写入底层输出流。
    voidwriteDouble使用doubleToLongBits类中的 方法将double参数转换为a Double,然后将该long值作为8字节数量(高字节优先)写入基础输出流。
    voidwriteChar(int v)将a char作为2字节值写入底层输出流,先写入高字节。
    voidwriteFloat(float v)int使用floatToIntBits类中的 方法将float参数转换为a Float,然后将该int值作为4字节数量,高字节优先写入基础输出流。
    voidwriteInt(int v)int底层输出流写为四个字节,高字节优先。
    voidwriteLong(long v)将a写入long基础输出流为8字节,高字节优先。
    voidwriteShort(int v)将a short作为两个字节写入底层输出流,高字节优先。
代码实例:
public class DataOutputStreamDemo { 	
    public static void main(String[] args) throws IOException {								
    	writeDemo();
		readDemo();	
    } 	
    public static void readDemo() throws IOException {		
        DataInputStream dos = new DataInputStream(new FileInputStream("data.txt"));			
        String s = dos.readUTF();		
        System.out.println(s);			
    } 	
    public static void writeDemo() throws IOException {		
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeUTF("你好啊");//UTF-8修改版

7.BufferedInputStream/BufferedOutputStream类

BufferedInputStream/BufferedOutputStream为IO提供了带缓冲区的操作,提高了IO的性能。

同样继承了InputStream和OutputStream。

BufferedInputStream的常用方法
  • 构造函数

    构造函数描述
    BufferedInputStream(InputStream in)创建BufferedInputStream 并保存其参数(输入流 in)供以后使用。
    BufferedInputStream(InputStream in, int size)创建BufferedInputStream 具有指定缓冲区大小的a,并保存其参数(输入流 in)供以后使用。
  • 常用方法

    1. close()
    2. read()
    3. read(byte[] d, int off , int length)

    用法同上

代码实例
//文件复制
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class A3 {

    public static void main(String[] args) throws IOException {

        String srefile = "D://imooc//io.txt" ;
        String destfile = "D://imooc//io1.txt" ;
        File file = new File( srefile ) ;
        File file2 = new File( destfile ) ;
        copyFile( file , file2 );

    }

    /**
     * 复制文件
     * @param srefile
     * @param destFile
     */
    public static void copyFile( File srefile , File destfile){
        InputStream inputStream = null ;
        BufferedInputStream bufferedInputStream = null ;

        OutputStream outputStream = null ;
        BufferedOutputStream bufferedOutputStream = null ;

        try {
            inputStream = new FileInputStream( srefile ) ;
            bufferedInputStream = new BufferedInputStream( inputStream ) ;

            outputStream = new FileOutputStream( destfile ) ;
            bufferedOutputStream = new BufferedOutputStream( outputStream ) ;

            byte[] b=new byte[1024];   //代表一次最多读取1KB的内容

            int length = 0 ; //代表实际读取的字节数
            while( (length = bufferedInputStream.read( b ) )!= -1 ){
                //length 代表实际读取的字节数
                bufferedOutputStream.write(b, 0, length );
            }
            //缓冲区的内容写入到文件
            bufferedOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {

            if( bufferedOutputStream != null ){
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if( bufferedInputStream != null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if( inputStream != null ){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if ( outputStream != null ) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

转载请注明:https://blog.csdn.net/qq_43544492/article/details/84934096

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值