createNewFile()与createTempFile()的不同

1, File 的 createNewFile() 方法: 
      createNewFile();返回值为 boolean;
方法介绍:当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
使用:
File file = new File("D:\\test\\1.txt");
boolean res = file.createNewFile();
if(!res)System.out.println("创建失败!");

如果D:/test 目录下没有 1.txt文件,则创建该文件;如果没有test目录,直接抛出异常,如果1.txt已经存在,那么文件创建失败。
可以得知,createNewFile() 方法,根据抽象路径创建一个新的空文件,当抽象路径制定的文件存在时,创建失败。
2,File 的 createTempFile() 方法

该方法有两种调用方式:
createTempFile(String prefix, String suffix);
在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。
createTempFile(String prefix, String suffix, File directory);
在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。

File file2 = new File("D:\\temp");// D;/temp 为一个目录
File tempFile1= file2.createTempFile("msg", ".tmp",file2);
File tempFile2 = file2.createTempFile("msg", ".tmp");
System.out.println(tempFile2.getAbsolutePath());

可以这么认为,createTempFile() 方法,在指定的目录下创建一个temp文件,directory 类型为File ,如果路径不存在,则创建失败。createTempFile(String prefix, String suffix);方法默认的保存路径为:C:\Documents and Settings\Administrator\Local Settings\Temp 

3.对tmp文件使用deleteOnExit方法。

File tmpFile = File.createTempFile("testrun-", ".xml", new File ("C:\\test"));
		Thread.sleep(5000);
		tmpFile.deleteOnExit();

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.

转载于:https://my.oschina.net/forrest420/blog/81521

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值