2021-04-08

文件字符字节流操作

下面主要讲解文件的字符字节的各种操作相应代码实现

一.文件字节流

1.文件字节输入流

public static void FileInfo() {
		try {
			FileInputStream in = new FileInputStream("D:\\刷课\\abc\\tt1.txt");
			
			byte[] b = new byte[1];
			int len = 0;
			
			while((len = in.read(b)) != -1) {
				System.out.print(new String(b,0,len));
			}
			
			in.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

2.文件字节流输出流

public static void testFioeoutputStream() {
		try {
			FileOutputStream out = new FileOutputStream("D:\\\\刷课\\\\abc\\\\tt4.txt");
			String str = "dawdagvawfgaw";
			out.write(str.getBytes());
			out.flush();
			out.close();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

3.文件字节流的复制

public static void copyFile(String inPath, String outPath) {
		try {
			FileInputStream in = new FileInputStream(inPath);
			
			FileOutputStream out = new FileOutputStream(outPath);
			byte[] b = new byte[100];
			
			int len = 0;
			
			while((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
			
			out.flush();
			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

二. 文件字符流

1.文件字符输入流

public static void testFileReader(String inPath) {//文件字符输入流
		try {
			FileReader fr = new FileReader(inPath);  //创建文件字符输入流的对象
			
			char[] c = new char[1000];    //创建临时存放数据的数组
			
			int len = 0;   //定义一个输入流的读取长度
			
			while((len = fr.read(c))!=-1) {
				
				System.out.println(new String(c, 0, len));
				
			}
			fr.close(); //关闭文件
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

2.文件字符输出流

public static void testFileWriter(String text,String outPath) { //文件字符输出流
		try {
			FileWriter fw = new FileWriter(outPath);
			fw.write(text); //将text写到内存
			fw.flush();  //将内存的数据刷到硬盘
			fw.close();  //关闭流
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

3.文件字符的复制

//字符流拷贝文件,inPath为需要拷贝的文件地址    outPath为拷贝后存入的文件地址
	public static void copyFile(String inPath, String outPath) {
		try {
			FileReader fr = new FileReader(inPath);
			FileWriter fw = new FileWriter(outPath);
			
			
			char[] c = new char[100];
			
			int len = 0;
			
			while((len = fr.read(c)) != -1){  //读取数据
				fw.write(c, 0, len);  //写入数据到内存
			}
			
			fw.flush();
			fr.close();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值