IO流

I/O流

IO:JAVA输入输出流,完成java应用程序和数据源(文件,内存,DB)之间进行数据交换

Java的IO流分类:

​ |—方向:输入和输出(相对于内存来说,往内存放入使用输入流,从内存中取使用输出流)

​ |—单位:字节流(每次读取一个字节),字符流(每次读取一个字符);如果实现多媒体数据读取使用字节流,读取文本文件使用字符流

​ |—功能:节点流(将应用程序和数据源连通,进行数据的读写),处理流(必须在节点基础上工作)

作用:完成应用程序和数据源文件,DB数据库之间数据的交换

分类:输入流(Input): 将文件加载到内存中

​ 输出流(Output):将内存数据写入到文件中

继承体系:
在这里插入图片描述在这里插入图片描述

FileOutputStream

将内存中的数据写到文件中(磁盘)

		//将内存中的数据写到文件中	
		String content = "Hello World !";
		//创建文件对象,指明要写入文件的路径
		File file = new File("E:\\file\\a\\b.txt");		
		//创建文件输出流
		/**
		 * 第一个参数为 需要写入的文件对象
		 * 第二个参数为  是否追加到写入内容之后
		 */
		FileOutputStream fileStream = new FileOutputStream(file,true);
		//方式1
		//获取到内容的字节数组
		byte[] bytes = content.getBytes();
		//将字节数组一个一个写入文件中
		for(byte b : bytes) {
			fileStream.write(b);
		}
		//方式2
		//将字节数组一次性写入文件中
		fileStream.write(bytes);

		fileStream.close();

FileInputStream

将文件中的内容写入到内存中

		//指明需要写入内存的文件目录
		File file = new File("E:\\file\\a\\a.txt");	
		//创建输入流
		FileInputStream fis = new FileInputStream(file);
		
		//方法一  
		//将文件中的内容读取到内存中
		int read = 0;
		//每次读取一个字节大小
		while((read = fis.read()) != -1) {
			char ch = (char)read;
			System.out.print(ch);
		}
		System.out.println();
		
		//方法二
		//指定每次读取9个字节
		byte[] b = new byte[9];
		int len = 0;
		while((len = fis.read(b)) != -1) {
			String str = new String(b,0,len);
			System.out.println(str);
		}
		
		fis.close();

FileWriter

字符输出流,将内存中的内容写到文件中

		String str = "你好,百度百科!";
		File file = new File("E:\\file\\b\\hello.txt");
		//判断文件是否
		if(file.exists()) {
			file.createNewFile();
		}
		
		FileWriter fw = new FileWriter(file,true);
		//方法1:直接写入字符串
		fw.write(str);
		
		//方法2 根据字符数组一次性写入
		char[] charArray = str.toCharArray();
		fw.write(charArray);
		
		//方法3  每次写入一个字符
		for(int i = 0 ;i < str.length();i ++) {
			char charAt = str.charAt(i);
			fw.write(charAt);
		}
		//释放资源
		fw.close();
		

FileReader

字符输入流,将文件中的内容加载到内存中

		//创建文件对象
		File file = new File("E:\\file\\b\\hello.txt");
		//创建字符文件输入流对象
		FileReader fd = new FileReader(file);
		
		
		//方法1  读出文件内容   每次读取一个字符
		int read = 0;
		while((read = fd.read()) != -1) {
			char ch = (char) read;
			System.out.print(ch);
		}	
		//方法2  每次读取9个字符
		char[] ch = new char[9];
		int len = 0;
		while((len = fd.read(ch)) != -1) {
			String str = new String(ch,0,len);
			System.out.print(str);
		}
		fd.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值