java读字节流 inputstream_JAVA之IO技术用字节流对文本文件进行读写FileInputStream,FileInputStream...

package ioTest.io2;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

/*

* IO:

* 字符流:Writer,Reader

* 字节流:OutPutStream,InPutStream

*

* 下面的实例仍然是对文本文件进行操作。但是字节流大多用于操作非文本文件,

* 比如音频视频图片等文件

*/

public class FileSteam {

public static void main(String[] args) throws IOException {

//writeFile();

readFile_3();

}

//三种不同的方式的读取文件

//读一个字节

public static void readFile_1() throws IOException {

FileInputStream fInputStream=new FileInputStream("ioTest1.txt");

int ch;

while((ch=fInputStream.read())!=-1)

{

System.out.println((char)ch);

}

fInputStream.close();

}

//读指定长度字节数组

public static void readFile_2() throws IOException {

byte[] buf=new byte[1024];

int len=0;

FileInputStream fInputStream=new FileInputStream("ioTest1.txt");

while((len=fInputStream.read(buf))!=-1)

{

System.out.println(new String(buf, 0, len));

}

fInputStream.close();

}

//读全长度的字节数组,也就是说一次性读取

public static void readFile_3() throws IOException {

FileInputStream fInputStream=new FileInputStream("ioTest1.txt");

int len=fInputStream.available();

byte[] buf=new byte[len];

fInputStream.read(buf);

System.out.println(new String(buf));

fInputStream.close();

}

/*

* 比较以上三种方式,第二种方式比第一方式更优越。

* 第三种方式在读写一些小文件的时候,看似是比前两种方式好。

* 但是文件很大的情况下,在第三种情况下,如果内存一次性不能存储这么大容量的文件时候

* 就会出现内存溢出。

* 所以最终和最常用的我们有限选择第二种方式。

*/

public static void writeFile() throws IOException {

//创建一个流

FileOutputStream foStream=new FileOutputStream("ioTest1.txt");

foStream.write("abcde".getBytes());

//foStream.flush();

//发现没有上面的话,仍然写入成功。原因是字节操作时读写操作的最小单位。

//所以这里暂时不用flush。字符操作实际上底层是基于字节的,所以又两个字节-一个字符的一个缓冲处理

//所以需要刷新

foStream.close();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值