ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

IO流进阶(输入输出流的批量读写)

2021-04-02 22:57:09  阅读:155  来源: 互联网

标签:outputStream 进阶 读写 bytes length IO new byte 字节


首先要定义读取文件地址和写入的文件地址
如下:

File fromFile=new File("D:/aaa.jpg");
File toFile=new File("E:/aaa.jpg");

之后需要定义一下输入输出流

InputStream inputStream= null;
OutputStream outputStream=null;

然后封装输入输出流

try {
			 inputStream=new FileInputStream(fromFile);
			 outputStream=new FileOutputStream(toFile);
			 }catch(FileNoFoundException e){
			 e.printStackTrace();{
			 }
			 

		
	}

封装完开始定义批量读写的格式
read() 从输入流读取数据下一个字节
read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。
write(byte[] b)将b.length个字节从指定的byte数组写入此输出流。

 byte[]bytes=new byte[2048];
			 //read每次批量的读取流的字节,将读到的批量字节缓存到byte数组中
			 //并返回实际读取的字节的个数,如果读到流的末尾则返回-1.
			 int length=-1;
			 while ((length=inputStream.read(bytes))!=-1) {
				System.out.println(Arrays.toString(bytes));
				System.out.println("此次读取的字节的个数="+length);
				//输出流批量写出
				//bytes要写出的字节的数组
				//0从字节数组的0下标开始写起
				//length 写出多少个字节
				outputStream.write(bytes,0,length);
				
			}

对于批量读写的严谨性 :outputStream.write(bytes,0,length);
输出流批量写出
bytes要写出的字节的数组
0从字节数组的0下标开始写起
length 写出多少个字节

最后,加入finally语句,结束。
关闭资源时需要注意,后使用完的先关闭。

源代码如下:

@Test
	public void  test2() {
		File fromFile=new File("D:/aaa.jpg");
		File toFile=new File("E:/aaa.jpg");
		InputStream inputStream= null;
		OutputStream outputStream=null;
		try {
			 inputStream=new FileInputStream(fromFile);
			 outputStream=new FileOutputStream(toFile);
			 //从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中
			 byte[]bytes=new byte[1024];
			 //read每次批量的读取流的字节,将读到的批量字节缓存到byte数组中
			 //并返回实际读取的字节的个数,如果读到流的末尾则返回-1.
			 int length=-1;
			 while ((length=inputStream.read(bytes))!=-1) {
				System.out.println(Arrays.toString(bytes));
				System.out.println("此次读取的字节的个数="+length);
				//输出流批量写出
				//bytes要写出的字节的数组
				//0从字节数组的0下标开始写起
				//length 写出多少个字节
				outputStream.write(bytes,0,length);
				
			}
			 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				//关闭资源,后使用完的先关闭
				if(outputStream!=null) {
					outputStream.close();
				}
				if(inputStream!=null) {
					inputStream.close();
					}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
		}
		
	}

标签:outputStream,进阶,读写,bytes,length,IO,new,byte,字节
来源: https://blog.csdn.net/qq_49218182/article/details/115408500

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有