Java基础面试题-6day

I/O流基础知识总结 (1)

io即输入输出流,
如何区分输入还是输入流
以内存为中介,当我们是将数据存储到内存即为输入,反之存储到外部存储器,即为输出
在Java中分输入输出流,根据数据处理又可以分为字节流和字符流

按输入输出流分
InputStream 字节输入流
Reader 字符输入流

OutputStream 字节输出流
Writer 字符输出流
以上都是抽象类

InputStream-字节输入流

try (InputStream fis = new FileInputStream("input.txt")) {
    System.out.println("Number of remaining bytes:"
            + fis.available()); 
	//FileInputStream对象调用available方法,返回
	//输入流中可以读取的字节数
    int content;
    long skip = fis.skip(2);
	//skip() 参数是忽略的输入流中的字节数,返回值是实际忽略的字节数
    System.out.println("The actual number of bytes skipped:" + skip);
    System.out.print("The content read from file:");
    while ((content = fis.read()) != -1) {
		//read() 方法读取输入流中的字节,返回下一个数据的值,范围是0~255
		// 当返回值是-1时,表示没有读取到 结束
        System.out.print((char) content);
    }
} catch (IOException e) {
    e.printStackTrace();
}
/
读取的文件,input.txt中写的是LLJavaGuide
结果是
Number of remaining bytes:11
The actual number of bytes skipped:2
The content read from file:JavaGuide



一般不会直接使用FileInputStream,而是会先使用BufferedInputStream字节缓冲输入流
例子

// 新建一个 BufferedInputStream 对象
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("input.txt"));
// 读取文件的内容并复制到 String 对象中
String result = new String(bufferedInputStream.readAllBytes());
//readAllBytes() 读取输入流中的所有字节,返回字节数组
System.out.println(result);

使用前提:必须以FileInputStream作为构造参数才能使用

FileInputStream fileInputStream = new FileInputStream("input.txt");
//必须将fileInputStream作为构造参数才能使用
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
//可以读取任意具体的类型数据
dataInputStream.readBoolean();
dataInputStream.readInt();
dataInputStream.readUTF();

在输入流中读取Java对象,称为反序列化
ObjectInputStream input = new ObjectInputStream(new FileInputStream("object.data"));
MyClass object = (MyClass) input.readObject();
input.close();

OutputStream-字节输出流

常见的方法
write(int b) 将特定的字节写入输出流
(byte b[ ]) 将数组b 写入输出流
(byte b[ ], int off ,int len)参数一表示要写入的字节数组,参数二是写入的起始位置,参数三是要读取的最大字节数
flush() 刷新此输出流并强制写出所有缓冲的输出字节
close() 关闭输出流,释放资源

try (FileOutputStream output = new FileOutputStream("output.txt")) {
    byte[] array = "JavaGuide".getBytes();
    output.write(array);
} catch (IOException e) {
    e.printStackTrace();
}

找到文件output.txt
其中的文本内容就是 JavaGuide

// 输出流
FileOutputStream fileOutputStream = new FileOutputStream("out.txt");
DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);
// 输出任意数据类型
dataOutputStream.writeBoolean(true);
dataOutputStream.writeByte(1);

将对象写入到输出流
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("file.txt")
Person person = new Person("Guide哥", "JavaGuide作者");
output.writeObject(person);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云来喜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值