文件读取的标准操作步骤:
1)创建源 2)选择流 3)操作 4)释放资源
FileInputStream & FileOutputStream 文件字节流
//FileInputStream
//1、创建源
File src = new File("abc.txt");
//2、选择流
InputStream is =null;
try {
is =new FileInputStream(src);
//3、操作 (读取)
/*int temp ;
while((temp=is.read())!=-1) {
System.out.println((char)temp);
}*/
(分段读取)
byte[] flush = new byte[1024*10]; //缓冲容器
int len = -1; //接收长度
while((len=is.read(flush))!=-1) { //读为空时返回-1
//字节数组-->字符串 (解码)
String str = new String(flush,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//4、释放资源
try {
if(null!=is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//FileOutputStream
//1、创建源
File dest = new File("dest.txt");
//2、选择流
OutputStream os =null;
try {
os = new FileOutputStream(dest,true);
//3、操作(写出)
String msg ="IO is so easy\r\n";
byte[] datas =msg.getBytes(); // 字符串-->字节数组(编码)
os.write(datas,0,datas.length);
os.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
//4、释放资源
try {
if (null != os) {
os.close();
}
} catch (Exception e) {
}
}
注意在写输出流的时候,在完成一次写操作时可调用flush()方法清除写在内存中的缓存。