java.IO系统file类中createNewFile FileInputStream的思考 - Go语言中文社区

java.IO系统file类中createNewFile FileInputStream的思考


     今天遇到一个问题,通过做实验终于明白,不知道对不对,和大家分享一下。

   问题是File file=new File(String path,String filename)file.createNewFile()什么区别 ,为什么有的文件创建后不用考虑file是否存在,而有的却要加上if(!file.exists()){}进行验证.

本人实验程序如下:

  

 

 

           import  java.io. * ;
public   class  file ...... {
 
public static void main(String arg[]) throws IOException ......{
     
//String s="mynameiszhangbin";
    
// byte buf[]=s.getBytes();
   File file=new File("d:/ajax1","my");
   
//FileOutputStream out=new FileOutputStream(file);
   
// out.write(buf,0,buf.length);
   
// out.close();
   if(!file.exists()) file.createNewFile();
     
   
   in.close();
}

   }

 

如果只是File file=new File("d:/ajax1","my")在d:/ajax1不会出现my文件,因此需用file.createNewFile()创建。

但是另外一种情况:

 

           import  java.io. * ;
public   class  file ... {
 
public static void main(String arg[]) throws IOException ...{
     String s
="mynameiszhangbin";
    
byte buf[]=s.getBytes();
   File file
=new File("d:/ajax1","my");
   FileOutputStream out
=new FileOutputStream(file);
    out.write(buf,
0,buf.length);
   out.close();
   
//if(!file.exists()) file.createNewFile();
     
   
   in.close();
}

   }

 

虽然没有用file.createNewFile()但是在d:/ajax1会出现my文件,因为我们进行了写文件(out.write())。

以上愚见,请指教。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/ZHANGBINFLY/article/details/2307971
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-04-11 21:55:34
  • 阅读 ( 554 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢