文件字节流FileInputStream,FileOutputStream

时间:2022-10-12 21:00:13

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();
			}
		}