Java实现对文件的读取以及编辑文件还有文件的拷贝

 代码实现了三个方法包括

readFile

writeFile

copyFile

package 读入写入拷贝;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

public class Text {
public static void readFile(String filename) {
	FileInputStream fi = null;
	try {
		fi = new FileInputStream(new File(filename));
		byte buffer[] = new byte[1024];
		int count = 0;
		while((count = fi.read(buffer))!=-1) {
			System.out.println("一共输入 "+count+" 个字节");
			System.out.println("读取文件原内容是:");
			System.out.println(new String(buffer,0,count,"UTF-8"));
			System.out.println("读取字节码为:");
			for(int i=0;i<count;i++) {
				System.out.print(buffer[i]+"  ");
			}
		}
	} catch (FileNotFoundException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}catch (IOException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}
}
public static void writefile(String text,File filename) {
	FileOutputStream fo = null;
	byte buffer[]=new byte[100];
	for (int i = 0;i<100;i++)
	{
		buffer[i] = (byte)new Random().nextInt(100);
	}
	try {
		fo = new FileOutputStream(filename);
		try {
			fo.write(buffer);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	} catch (FileNotFoundException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}
	//  byte b[]=null;
//	try {
//		b=text.getBytes("UTF-8");
//		try {
//			fo = new FileOutputStream(filename);
//		} catch (FileNotFoundException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
//		fo.write(b);
//		if(fo!= null)
//		{
//			fo.close();
//		}
//	} catch (UnsupportedEncodingException e) {
		// TODO 自动生成的 catch 块
//		e.printStackTrace();
//	} catch (IOException e) {
//		// TODO 自动生成的 catch 块
//		e.printStackTrace();
//	}
}
public static void filecopy(File source,File destination) {
	byte buffer[] = new byte[1024];
	FileInputStream fi = null;
	FileOutputStream fo= null;
	int count = 0;
	try {
		fi = new FileInputStream(source);
		fo = new FileOutputStream(destination);
		while((count = fi.read(buffer))!=-1) {
			fo.write(buffer, 0, count);
		}
	} catch (FileNotFoundException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}catch (IOException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}
	
}
	
	
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
readFile("D:/tools/mydream.txt");
  String text =null;
//String text = "我爱茜茜茜茜";
writefile(text,new File("D:/tools/mydata.txt"));
filecopy(new File("D:/tools/MyDream.txt"), new File("D:/tools/newMyDream.txt"));
	}

}

简单的输入输出流操作

如有错误,欢迎指正。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值