文件字节流FileInputStream,FileOutputStream

1.从文件读取信息到内存(字节)

        File f = new File("/Users/hh/Desktop/test豆腐缶122.txt");
		//因为file没有读写的能力,所以需要FileInputStream
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(f);
			//定义一个字节数组,相当于缓存
			byte []bytes = new byte[1024];
			int n = 0;//得到实际读取到的字节数
			//循环读取
			while ((n = fis.read(bytes))!= -1) {
				//把字节转成string
				String s = new String(bytes,0,n);
				System.out.println(s);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//关闭文件流必须放在这里
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

2.从内存读取信息到文件

            File f =  new File("/Users/hh/Desktop/test11.txt");
		//字节输出流
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(f);
			String s = "林玉,女,汉族,育有一女,可可。\r\n";
			String s1 = "吴晓龙是个胖子";
			byte []b = new byte[1024];//刚好1k;
			//如何把String转化成Bytes数组
			byte []bytes = s.getBytes();
			fos.write(bytes);
			fos.write(s1.getBytes());
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				fos.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

3.字节流有两种创建方式

(1)先创建文件,在生成字节流

File f =  new File("/Users/hh/Desktop/test11.txt");
FileOutputStream fos = new FileOutputStream(f);

(2)直接创建字节流

FileInputStream fis = new FileInputStream("/Users/hh/Desktop/img-180207150924.jpg");

4.图片拷贝

                //思路 先把图片读入到内存--》写入到某个文件
		//因为是二进制文件,所以只能用字节流完成
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("/Users/hh/Desktop/img-180207150924.jpg");
			fos = new FileOutputStream("/Users/hh/Desktop/临时版本/营业执照扫描件.jpg");
			byte []bytes = new byte[1024];
			int n = 0;//记录实际读取到的字节数
			//循环读取
			while ((n=fis.read(bytes))!=-1) {
				//输出到制定文件
				fos.write(bytes);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值