日期:2014-05-20  浏览次数:21006 次

如何创建一个文件可以覆盖原来的文件,如果它存在?
File   f   =   new   File(nextFile, "x.txt ");  
        if(!f.exists())  
        {  
          f.createNewFile();  
        }  
       
看到好多代码都是这样的。

而我现在想创建一个新文件时,如果这文件存在,就覆盖它,重新开始从头写。

怎么做那?

thanks!

------解决方案--------------------
那就是那么写的啊。

------解决方案--------------------
<code> true </code> if the named file does not exist and was
successfully created; <code> false </code> if the named file
already exists

存在的话就返回false了.
------解决方案--------------------
如果存在就删除
再写新的
------解决方案--------------------
赞同彩虹勇士
File f = new File(nextFile, "x.txt ");
if(f.exists())
{
f.delete();
}
f.createNewFile();


------解决方案--------------------
if(f.exists())
{
f.delete();
}
f.createNewFile();
/////////////////////////////////////////
这样最保险
------解决方案--------------------
使用FileOutputStream 或 FileWriter创建文件输出流对象时,Java系统不论语句中指定的文件是否存在,都会创建一个。因此,为了避免将数据写入一个已经存在的文件中(它会覆盖文件中的原有内容),程序中一般需要使用File对象来判断某个文件是否已经存在。
------解决方案--------------------
同楼上,也就是说,直接这样就行了

File f = new File(nextFile, "x.txt ");
f.createNewFile();
------解决方案--------------------
其实什么判断都不需要,只要
File f = new File( "newfile.txt ");
FileOutputStream fout = new FileOutputStream(f);
就可以了,根本不用关心是否存在,它会自己处理
------解决方案--------------------

同意ls的,也只有同意ls的!!!!!!!!!!!!!!!!!!!!!!!!