File f = new File(nextFile,"x.txt"); 
    if(!f.exists()) 
    { 
     f.createNewFile(); 
    } 
    
看到好多代码都是这样的。而我现在想创建一个新文件时,如果这文件存在,就覆盖它,重新开始从头写。怎么做那?thanks!

解决方案 »

  1.   

    这个是如果存在就不动了。想试试不加判断,直接 f.createNewFile() 不知道行不行。看文档上好像不行。只好明天再试了。
      

  2.   

    <code>true</code> if the named file does not exist and was
     successfully created; <code>false</code> if the named file
    already exists存在的话就返回false了.
      

  3.   

    赞同彩虹勇士 
    File f = new File(nextFile,"x.txt"); 
    if(f.exists()) 

       f.delete();
    }
    f.createNewFile(); 
     
      

  4.   

    if(f.exists()) 

       f.delete();
    }
    f.createNewFile(); 
    /////////////////////////////////////////
    这样最保险
      

  5.   

    使用FileOutputStream 或 FileWriter创建文件输出流对象时,Java系统不论语句中指定的文件是否存在,都会创建一个。因此,为了避免将数据写入一个已经存在的文件中(它会覆盖文件中的原有内容),程序中一般需要使用File对象来判断某个文件是否已经存在。
      

  6.   

    同楼上,也就是说,直接这样就行了File f = new File(nextFile,"x.txt"); 
    f.createNewFile();
      

  7.   

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

  8.   


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