JavaSE 文件与IO 流

代表有能力产生数据的数据源对象或者有能力接收数据的接收端对象。
面向字节:

  • InputStream
  • OutputStream

面向字符:

  • Reader
  • Writer

InputStream OutputStream 字节流

不同的数据源有不同的InputStream子类与之对应

作用
FileInputStream从文件中读取信息
StringBufferInputStream将String转换为InputStream
SequenceInputStream将两个及以上InputStream转换为单一的InputStream
ByteArrayInputStream将内存缓冲区当作InputStream
PipeInputStream实现管道化概念
FilterInputStream抽象类作为装饰器的接口

FilterInputStream
装饰器修改流满足特殊需求

  • DataInputStream 与 DataOutputStream搭配使用,按照可移植的方式读取基本数据类型
  • BufferedInputStream 防止每次读取缓冲区时都要进行写操作

使用

  • 文件字节输出流 向磁盘中写入数据
public static void main(String[] args) throws IOException {
		//不存在直接创建
		File f = new File("d:/a.txt");
		byte[] data = {0,1,2};
		FileOutputStream fo = new FileOutputStream(f);
		fo.write(data);
		fo.close();
		//当多级目录不存在会报错
		//解决方法→获取父路径 mkdirs
		File f2 = new File("d:/a/b/c/a.txt");
		File f3 = new File(f2.getParent());
		f3.mkdirs();
		FileOutputStream fo2 = new FileOutputStream(f2);
		fo2.write(data);
		fo2.close();
  • 文件字节输入流 从磁盘中读数据
public static void main(String[] args) throws IOException {
		File f = new File("d:/a/b/c/a.txt");
		FileInputStream fi = new FileInputStream(f);
		byte[] b = new byte[100];
		fi.read(b);
		for(byte by:b) {
			System.out.println(by);
		}
		fi.close();

	}
  • 关闭流的标准方式 finally

https://how2j.cn/k/io/io-closestream/682.html?p=105150在这里插入图片描述

package stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class TestStream {

	public static void main(String[] args) {
		File f = new File("d:/lol.txt");
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(f);
			byte[] all = new byte[(int) f.length()];
			fis.read(all);
			for (byte b : all) {
				System.out.println(b);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 在finally 里关闭流
			if (null != fis)
				try {

					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

	}
}


Writer Reader 字符流

  • 字节流与字符流的转换
    InputStreamReader把InputStream转换为Reader
    OutputStreamWriter把OutputStream转换为Writer

  • 写入数据

public static void main(String[] args) throws IOException {
		
		File f = new File("d:/a/b/c/a.txt");
		File fNew = new File(f.getParent());
		fNew.mkdirs();
		FileWriter fo2 = new FileWriter(f);
		//开始写入
		String data = "123zjnhahaha";
		fo2.write(data);
		fo2.close();

在这里插入图片描述

  • 读取数据
public static void main(String[] args) throws IOException {
		File f = new File("d:/a/b/c/a.txt");
		FileReader fi = new FileReader(f);
		char[] b = new char[20];
		fi.read(b);
		for(char c:b) {
			System.out.print(c);
		}
		fi.close();

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值