Java中字节流的总结及代码练习

2022/8/25 14:23:26

本文主要是介绍Java中字节流的总结及代码练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java中的字节流

在描述字节流时,先知道什么是流

流可以分为:输入流和输出流

输入流和输出流 示意图:img

字节流读取内容:二进制,音频,视频

优缺点:可以保证视频音频无损,效率低,没有缓冲区

字节流可以分为:InputStream(字节输入流) 和 OutputStream(字节输出流)

InputStream是所有类字节输入流的超类其下的类有:

FileInputStream(文件输入流),

BufferedInputStream(缓冲字节输入流),

ObjectInputStream(对象字节输入流,它的直接父类是FilterInputStream);

举几个常用类的方法

FileInputStream方法有:

read():从此输入流中读取一个数据字节

read(byte[] b):从此输入流中将最多读b.length个字节的数据读入到一个byte[]数组中,读取正常,返回实际读取的字节数new String(new byte[1024],0,readlen),读到最后一个字节返回-1,有利于提高效率

read(byte[],int off, int len):这个方法可以读取里面部分内容,内容为off到len之间的内容

OutputStream也是顶级父类其下的类有:

FileOutputStream:new FileOutputStream(pathname)创建方式,当写入内容时会自动覆盖原内容

new FileOutputStream(pathname,true)此方式在原来内容上缀加内容,而不会覆盖

BufferedOutputStream,

ObjectOutputStream;

FileOutputStream:将数据写到文件中,如果该文件不存在,则自动创建该文件

FileOutputStream方法有:

write():写入单个字节

write(str.getbytes()):将字符串转成字符数组输出出来 str.getbytes()=byte[] b;

write(str.getbytes(), int off,str.length()):将len字节从位于偏移量 off的指定字节数组写入此文件输出流

字节流的综合练习:将d盘里a.txt文件拷贝到e盘

public static void main(String[] args) {
		// TODO Auto-generated method stub
        //1.创建文件的输入流
		FileInputStream fis=null;
		FileOutputStream fos=null;
		String pathname="D:\\a.txt";
		String pathname1="E:\\a.txt";
	    try {
	    	fis=new FileInputStream(pathname);//文件的输入流
			fos=new FileOutputStream(pathname1);
	    	byte[] b=new byte[1024];
	    	int readlen=0;
	    	while((readlen=fis.read(b))!=-1){
	    		fos.write(b,0,readlen);
	    	}
	    	System.out.println("拷贝成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(fos!=null){
					fos.close();
				}
				if(fis!=null){
					fis.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
			
		}
		
	}


这篇关于Java中字节流的总结及代码练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程