java 字节流字符流读写

字节流和字符流的区别:

字节流就是可以读取图片,文本,视频等二进制数据;字符流只能读取纯文本文件。

字节流读写示例:

public static void main(String[] args) {
		String path = "D:/study_project/1.jpg";
		String path1 = "D:/study_project/2.jpg";
		String path2 = "D:/study_project/java-io-test.txt";
		String path3 = "D:/study_project/java-io-test-to.txt";
//		readTxt(path2);
		writeFile(path2,path3);

	}
/**
	 * 文件的写入:
	 * @param fromPath 源
	 * @param toPath   目标
	 */
	public static void writeFile(String fromPath,String toPath) {
		BufferedInputStream fis = null;
		BufferedOutputStream fos = null;
		int len = 2;
		byte[] buffer = new byte[len];
		try {
			fis = new BufferedInputStream(new FileInputStream(fromPath));
			fos = new BufferedOutputStream(new FileOutputStream(toPath));
			while ((fis.read(buffer, 0, len)!=-1) && buffer.length > 0) {
				fos.write(buffer, 0, buffer.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件没有找到");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取异常");
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (Exception e2) {
				System.out.println(e2);
			}
		}
	}


字符流读写:

public static void main(String[] args) {
		
		String path = "D:/study_project/1.jpg";
		String path1 = "D:/study_project/2.jpg";
		String path2 = "D:/study_project/java-io-test.txt";
		String path3 = "D:/study_project/java-io-test-to.txt";
		
		readChar(path2,path3);
	}
	public static void readChar(String fromPath,String toPath){
		BufferedReader read  = null;
		BufferedWriter write  = null;
		int len = 20;
		char[] buffer = new char[len];
		try {
			read =  new BufferedReader(new InputStreamReader(new FileInputStream(fromPath), "utf8"));
			write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toPath),"utf8"));
			while ((read.read(buffer, 0, len)!=-1) && buffer.length > 0) {
				write.write(buffer, 0, len);
			}
			write.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件没有找到");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取异常");
		} finally {
			try {
				read.close();
				write.close();
			} catch (Exception e2) {
				System.out.println(e2);
			}
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值