您的位置:首页 > 其它

3中文件读取方式

2015-09-13 20:32 288 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: