实例代码三(文件读取,字节流和字符流)

本文通过两个Java程序示例展示了如何使用字符流和字节流进行文件复制。字符流复制利用FileReader和FileWriter实现文本文件的一对一复制;字节流复制则通过FileInputStream和FileOutputStream完成,适用于二进制文件的复制。

就是复制文件到另一个文件,字节流和字符流的读取

读取字符
import java.io.*;
public class ZifuDemo {
	public static void main(String[] args) {
		FileReader in=null;
		FileWriter out=null;
		int b;
		char a;
		try {
			in=new FileReader("C:/keshe/oldone.txt");
			out=new FileWriter("C:/keshe/newone2.txt");
			while((b=in.read())!=-1) {
				a=(char)b;
				out.write(a);}
			in.close();
			out.close();
		}catch(FileNotFoundException e){
			System.out.println("can not find file!");
		}catch(IOException e1) {
			System.out.println("File read error!");}}}
读取字节
import java.io.*;
public class ZijieDemo {
	public static void main(String[] args) {
		FileInputStream in=null;
		int b=0,count=0;
		char a;
		FileOutputStream out=null;
		try {
			out=new FileOutputStream("C:/keshe/newone1.txt");
			in=new FileInputStream("C:/keshe/oldone.txt");	
		}catch(FileNotFoundException e) {
			System.out.println("can not find file!");
			System.exit(-1);}
		try {
			while((b=in.read())!=-1) {
				a=(char)b;
				out.write(a);}
			in.close();
			out.close();
		}catch(IOException e1){
			System.out.println("File read error!");
			System.exit(-1);}}}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值