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;
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();
}