java的输入输出流与文件操作(2.读入写出及关流)

1.如何读取文件。

可以一个字节一个字节的读,也可以使用缓冲,一块一块数据的读。

一般使用第二种,因为比较快。

@Test
	public void TestRead() throws IOException {
		byte buf[] = new byte[1024];
		FileInputStream fin = new FileInputStream("E:/test/io.txt");
		int len = 0;
		while((len=fin.read(buf)) != -1){
			for (int i = 0; i < len; i++) {
				System.out.print((char)buf[i]);
			}
		}
		fin.close();
	}

2.如何写出文件。

写出文件可以追加写出,也可以重新写出。

追加写出就是在原来文件的基础上继续追加内容。

重新写出就是擦除原来的文件内容,将新的内容写出到文件。

具体操作看代码。

@Test
	public void TestOut() throws IOException{
		byte buf[] = {65,66,49,48,13,10,97,98};
		// FileOutputStream fout = new FileOutputStream("E:/test/io.txt");//重新写出方式
		FileOutputStream fout = new FileOutputStream("E:/test/io.txt",true);//追加方式
		fout.write(buf);
		fout.close();
		/* 控制台打印:
		 * AB10
		 * ab
		 * */
	}

3.使用流之后关流的正确操作(IO异常处理的模板)

@Test
	public void TestClose() {
		byte buf[] = new byte[512];
		int len = 0;
		FileInputStream in = null;
		try {
			in = new FileInputStream("E:/test/io.txt");
			while ((len = in.read(buf)) != -1) {
				// bytes, offset, length ,charsetName
				String string = new String(buf, 0, len, "gbk");
				System.out.print(string);
			}
		} catch (FileNotFoundException e) {
			System.err.println("找不到指定文件!");
			// e.printStackTrace();
		} catch (IOException e) {
			System.err.println("文件读取失败");
			// e.printStackTrace();
		} catch (Exception e) {
			// 作为补充
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {// 不能为空(反正有点的都需要防护)
					in.close();
				}
			} catch (IOException e) {
				// 到这里情节已经很严重了,可能会丢失数据
				throw new RuntimeException("关流失败",e);
			}
		}
	}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值