码迷,mamicode.com
首页 > 其他好文 > 详细

IO流

时间:2014-11-15 00:07:44      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:io   ar   使用   java   for   文件   数据   cti   bs   

文件流读取的步骤:
1、创建文件File对象,判断是否存在,不存在直接退出
2、创建文件流对象FileInputStream,通过文件对象构造
3、创建byte[]数组对象,数组长度为文件的大小长度
4、文件流对象read(byte[] bts)方法,一次性读取文件数据
5、关闭文件流
6、将byte[]数组对象转换成String:String str=new String(bts);

针对大文件读取,使用每次固定长度的方式读取数据:
1、创建文件流对象fileinputStream,
2、创建固定大小的byte[]数组对象,建议长度定为1024;
3、循环读取数据:read(byte[] bts,0,长度),如fis.read(bts,0,bts.length)!=-1
4、将bts数组对象转换字符串对象
5、关闭文件流
IO:
文件流操作:需要导入JAVA.IO包
File类:可对文件和文件夹进行相关属性的操作,如获取大小、文件名、路径等,常用的方法:exists(),getName(),length(),isFile(),isDrectory(),listFiles();

文件流:按照流的流向分为:输入流和输出流
按照数据格式分为:字节流和字符流
字节流:
FileInputStream:读文件
读取文件时返回byte[]数组对象,read(byte[] bt)
FileOutputStream:写文件
写入文件时使用byte[]数组对象,write(byte[] bt)

字符流:
FileReader:读文件+BufferedReader:缓冲读取对象
FileReader fr=new FileReader("文件名");
BufferedReader br=new BufferedReader(fr);
读文件时:br.readLine();一行一行读取数据
while((str=br.readLine())!=null){
}
FileWriter:写文件+BufferedWriter:缓冲写入对象
FileWriter fw=new FileWriter:("文件名");
BufferedWriter bw=new BufferedWriter(fw);
写文件时:bw.write("字符串");

基础数据流的操作:
DataInputStream和DataOutputStream

对象序列化的操作:
ObjectInputStream和ObjectOutputStream

配置文件的操作:
Properties保存时:FileOutputStream
读取时:FileInputStream
1、File类:可以操作文件和文件夹的对象
常用的方法:exists(),delete(),createNewFile(),length(),isFile(),isDirectory(),getAbsolutePath(),getName(),listFile()
2、字节输入流:FileInputStream,输入数据到内存中
操作步骤:
File file=new File("");
FileInputStream fis=new FileInputStream(file);
第一种:一次性读取
byte[] bts=new byte[(int)file.length()];
fis.read(bts);
第二种:一次读取一个字节
int len=(int)file.length();
for(int i=0;i<len;i++){
char c=(char)fis.read();
}
第三种:固定长度读取
int len=(int)file.length();
int size=len>1024?1024:len;
byte[] bts=new byte[size];
int count=0;
while((count=fis.read(bts,0,size))!=-1){}

3、字节输出流:FileOutputStream,输出数据到存储介质中
操作步骤:
File file=new File("");
FileOutputStream out=new FileOutputStream(file);
String str="输出的内容";
第一种:一次输出一个字节
char[] chs=str.toCharArray();
for(char c:chs){
out.write(c);
}
第二种:一次性输出
byte[] bts=str.getBytes();
out.write(bts);

4、字符输入流:FileReader,
缓冲区输入流:BufferedReader
操作步骤:
File file=new File("");
FileReader read=new FileReader(file);
BufferedReader br=new BufferedReader(read);
String str="";
while((str=br.readLine())!=null){
}

5、字符输出流:FileWriter,
缓冲区输出流:BufferedWriter
操作步骤:
File file=new File("");
FileWriter fw=new FileWriter(file);
BufferedWriter br=new BufferedWriter(fw);
String str="要输出的内容";
br.write(str);

IO流

标签:io   ar   使用   java   for   文件   数据   cti   bs   

原文地址:http://www.cnblogs.com/JAYIT/p/4098321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!