File FilecreateNewFile()和createTempFile()的区别

createNewFile()和createTempFile()区别:

为了更好地测试,我建了两个类:

 

1、使用createNewFile()创建一个abc.txt的文件:

Java代码      收藏代码
  1. public class TestFile1 {  
  2.       
  3.     public static void main(String[] args) {  
  4.         File f1 = new File("C:\\abc.txt");  
  5.         try {  
  6.             f1.createNewFile();  
  7.             System.out.println(f1.getName());  
  8.         } catch (IOException e) {  
  9.             e.printStackTrace();  
  10.         }  
  11.     }  
  12.   
  13. }  

 

 

控制台输出:
abc.txt

 

2、使用createTempFile()创建一个abc.txt的文件:

Java代码      收藏代码
  1. public class TestFile2 {  
  2.       
  3.     public static void main(String[] args) {  
  4.         File f1 = new File("C:\\");  
  5.         File f2 = null;  
  6.         try {  
  7.             f2 = File.createTempFile("abc"".txt", f1);  
  8.             System.out.println(f2.getName());  
  9.         } catch (IOException e) {  
  10.             e.printStackTrace();  
  11.         }  
  12.     }  
  13.   
  14. }  

 
控制台输出:

但是我查看了指定路径,生成了

abc4825787091196303263.txt文件,每一次执行,都能生成不同的文件,但中间的数字都是19位,我查看了Java的File源代码,按住Ctrl+鼠标左击,进入File.class,看到有

Java代码      收藏代码
  1. private static File generateFile(String prefix, String suffix, File dir)  
  2.         throws IOException  
  3.     {  
  4.         long n = LazyInitialization.random.nextLong();  
  5.         if (n == Long.MIN_VALUE) {  
  6.             n = 0;      // corner case  
  7.         } else {  
  8.             n = Math.abs(n);  
  9.         }  
  10.         return new File(dir, prefix + Long.toString(n) + suffix);  
  11.     }  

 

Java代码      收藏代码
  1.    public static File createTempFile(String prefix, String suffix,  
  2.                   File directory)  
  3.        throws IOException  
  4.    {  
  5. if (prefix == nullthrow new NullPointerException();  
  6. if (prefix.length() < 3)  
  7.     throw new IllegalArgumentException("Prefix string too short");  
  8. String s = (suffix == null) ? ".tmp" : suffix;  
  9. if (directory == null) {  
  10.            String tmpDir = LazyInitialization.temporaryDirectory();  
  11.     directory = new File(tmpDir, fs.prefixLength(tmpDir));  
  12. }  
  13. SecurityManager sm = System.getSecurityManager();  
  14. File f;  
  15. do {  
  16.     f = generateFile(prefix, s, directory);  
  17. while (!checkAndCreate(f.getPath(), sm));  
  18. return f;  
  19.    }  

 注意函数generateFile()的返回值是new File(dir, prefix + Long.toString(n) + suffix);

由此可明白为什么会生成abc4825787091196303263.txt文件了。

 

 

但还有个问题,如果使用createTempFile()创建文件时,中间的数字串是个问题,我还没解决,朋友,你能解决么?欢迎指导……

转自:http://itssff-yahoo-cn.iteye.com/blog/966536

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值