inputSream和outStream

关闭资源的时候按照先开后关后开先关的顺序同时在判断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();

                                    }

} catch (IOException e) {

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





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值