(一)读
(1)按字节读
InputStream is = new FileInputStream(file);
while((temp=is.read())!=-1){}
按字节数组读
<span style="font-size:18px;">byte[] arr = new byte[20];
InputStream is = new FileInputStream(file);
while((temp=is.read(arr))!=-1){} //从输入流中读取一定数量的字节,并将其存储在缓冲区数组arr中</span>
(2)按字符读
Reader r = new FileReader(file);
while((temp=r.read())!=-1){
sb.append((char)temp);
}
(3)按行读
BufferedReader br = new BufferedReader(new FileReader(file));
while((temp=br.readLine())!=null){}
(二)写
(1)FileOutputStream
用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。
FileOutputStream fos = new FileOutputStream(file);
fos.write('i'); //int or byte
(2)BufferedOutputStream
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write('i'); //int or byte
(3)FileWriter
字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容
FileWriter fw = new FileWriter(file);
//FileWriter(String fileName,boolean append)根据给定的文件名以及指示是否附加写入数据的 boolean值来构造 FileWriter对象
fw.write("int char[] string");
(4)BufferedWriter
BufferedWriter bw = new BufferedWriter(fw);
bw.write("char[] int string");