关闭资源的时候:按照先开后关,后开先关的顺序,同时在判断io对象不为null之后再执行.colse()方法,因为假如io对象为空,那么执行io.close()方法会出现空指针异常
inputStream
由于inputStream是基类,所以我们一般使用FileInputStream
文件写入流,把数据用字节流的方式从源文件读取到内存中
构造方法:
File inputSream(File file) //读取文件的文件名
File inputSream(String name)//写要读取文件的地址名
方法:
read() //逐个读取源文件字节,返回int代表读取的数据字节;如果已到达文件末尾,则返回 -1
read(byte[] b)//字节读取到一个数组中,int 返回实际读取字节数
read(byte[] b ,int off,int len)//把字节读到数组中,从数组off下标开始读len个字节,int返回实际读取字节数
close() //关闭输入流
available() //返回字节流可读取的字节数
示例:
//创建对象
FileInputStream stream = null;
try {
//指向子类对象
stream= new FileInputStream("d:/11.txt");
//用一个int变量接受返回的int值
int leng;while((leng=(stream.read()))!=-1){
System.out.println((char)leng);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
//记得要关闭数据流,同时要判断是否为空现象
//因为假如io对象为空,那么执行io.close()方法会出现空指针异常
if(stream!=null){
stream.close();
}
e.printStackTrace();
outputStream
由于outputStream是基类,所以我们一般使用FileoutputStream
构造方法:
File outputSream(File file) //写入文件的文件名
File outputSream(String name)//要写入文件的地址名
方法:
write() //逐个字节将内容写入目标文件
write(byte[] b ) //将数组中的字节写入目标文件
write(byte[] b ,int off, int len)//将数组中的字节写入目标文件,写入长度为len,从off开始
close() //关闭输出流,会先调用fulsh()方法先
flush() //清空缓存区
示例:将从d盘下的文件内容,复制到E盘底下的文件中
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("d:/11.txt");
fos = new FileOutputStream("e:/new.txt");
byte[] b = new byte[1000];
int lean;
//注意这里read已经将内容写入b中了
while ((lean=(fis.read(b)))!=-1) {
fos.write(b, 0, lean);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis!=null){
fis.close();
}
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();