Java的各种流啊~待更中

1、简单输入输出流

对文件内容进行追加写,利用字节数组做缓冲区

package com.hpu.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * new FileOutputStream(String path,boolean append);
 * append设置true,代表对文件是追加写
 * @author Administrator
 */
public class TestCopy {
	public static void main(String[] args) {
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
	    try {
	    	//获取输入输出流
			inputStream = new FileInputStream("C:\\Users\\Administrator.PCOS-1901021312\\Desktop\\reborn.jpg");
			outputStream = new FileOutputStream("D:\\文件\\hpu_java_code\\day6\\aaa.jpg");
			//定义缓冲区
			byte [] buffer=new byte[1024];
			//定义一个长度变量
			int length=0;
			/**
			 * 不知道源文件具体的大小,所以使用while循环读取
			 * 1025=1024+1;
			 * 当读取到文件末尾时,返回为-1
			 */
			while((length=inputStream.read(buffer))!=-1){
				outputStream.write(buffer, 0, length);
			}
			//outputStream.flush();清缓冲区,关闭时会清,可不写
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			//避免空指针异常
			try {
				if(inputStream!=null){
					inputStream.close();
				}
				if(outputStream!=null){
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}		
	}
}

2、实现按行读取,使用字符流读写缓冲装饰流

package com.hpu.readerwriter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

//按行读取
public class TestReader {
	public static void main(String[] args) {
		BufferedReader br=null;
		BufferedWriter bw=null;
		try {
			FileReader fileReader = new FileReader("D:\\文件\\hpu_java_code\\day6\\文件\\lala.txt");
			FileWriter fileWriter = new FileWriter("D:\\文件\\hpu_java_code\\day6\\文件\\write.txt");
			//使用字符流读写缓冲装饰流
			br = new BufferedReader(fileReader); 
			bw = new BufferedWriter(fileWriter);
			String str=null;
			//一次读取一行
			while((str=br.readLine())!=null){
				/**
				 * str可以取到read.txt文件中的每行数据
				 * 将str写入到write.txt文件中
				 */
				bw.write(str);
				bw.newLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(br!=null){
					br.close();
				}
				if(bw!=null){
					bw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值