您的位置:首页 > 编程语言 > Java开发

Java IO流基础

2016-06-28 16:14 549 查看

1.字节流(byte stream):为处理字节的输入和输出提供了方便的方法。例如使用字节流读取或书写二进制数据。

2.字符流(character stream):为字符的输入和输出处理提供了方便。

字节流/字符流:Java中,以stream结尾的都为字节流,以reader、writer结尾的为字符流。

注:在最底层,所有的输入/输出都是字节形式的。

字节流/字符流读、写文件代码如下

private String filePath="F:/java测试.txt";

/**
*
* @Description:用字节流读取文件
* @throws IOException: 返回结果描述
* @return void: 返回值类型
* @throws
*/
public void readFileByByte() throws IOException{
//读取文件
FileInputStream fis=new FileInputStream(filePath);
//估算文件的长度
int size = fis.available();
for (int i=0;i<size;i++) {
//读取每个字节的数据
char a=(char) fis.read();
System.out.println(a);
}
//关闭输入流
fis.close();
}

/**
*
* @Description:字符流读取文件
* @throws IOException: 返回结果描述
* @return void: 返回值类型
* @throws
*/
public void readFileByCharacter() throws IOException{
//创建字符流文件读取对象
FileReader fr=new FileReader(filePath);
//为文件读取对象建立缓冲区
BufferedReader br=new BufferedReader(fr);
String str=null;
//br.readLine()从文件中读取一行数据,以回车为结束符,如果没有可读数据返回null
while((str=br.readLine())!=null){
System.out.println(str);
}
//关闭流
br.close();
fr.close();
}

/**
*
* @Description:用字节流写文件
* @throws IOException: 返回结果描述
* @return void: 返回值类型
* @throws
*/
public void writeFileByByte() throws IOException{
//写文件
FileOutputStream fos=new FileOutputStream(filePath);
String str="站在java的角度来记忆,文件输出流为FileOutputStream,文件输入流为FileInputStream";
byte[] b=str.getBytes();
fos.write(b);//写入目标文件
fos.close();//关闭输出流
}

/**
*
* @Description:字符流写文件
* @throws IOException: 返回结果描述
* @return void: 返回值类型
* @throws
*/
public void writeFileByCharacter() throws IOException{
FileWriter fw=new FileWriter(filePath);//创建文件写入对象
String str="站在java的角度来记忆,文件输出流为FileOutputStream,文件输入流为FileInputStream";
fw.write(str);
fw.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: