import java.io.*;public class testfile1{
  public static void main(String[] args){
     String separator=File.separator;
     String filename="myfile.txt";
     String directory="mydir1"+separator+"mydir2";
     File f=new File(directory,filename);
     if(f.exists()){
        System.out.println("文件名:"+f.getAbsolutePath());
        System.out.println("文件大小:"+f.length());
     }else{
        f.getParentFile().mkdirs();         
        try{
           f.createNewFile();
        }catch(IOException e){    //注释处
           e.printStackTrace();  
        }
     }
  }

}
//注释处如果抛出异常,比如说会抛出什么样的异常?
我在当前目录起了一个和他同名的文件或文件夹,也没抛异常呢?

解决方案 »

  1.   

    你的try/catch只是捕获
    try{
    f.createNewFile();
    }catch(IOException e){ //注释处
    e.printStackTrace();   
    }
    只是捕获createNewFile()这个方法,而且即使你已经有了相同的文件或者文件目录,createNewFile也不会报错,会覆盖掉你原来的,没有产生异常
      

  2.   

    Throws: 
    IOException - If an I/O error occurred 
    SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file
      

  3.   

    API说
    createNewFile方法:当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。检查文件是否存在,若不存在则创建该文件,这是单个操作,对于其他所有可能影响该文件的文件系统活动来说,该操作是不可分的。 
      

  4.   

    API还说
    返回:
    如果指定的文件不存在并成功地创建,则返回 true;如果指定的文件已经存在,则返回 false 所以,即使存在也只是返回一个false,不会有异常的。
      

  5.   

    建议你好好看看API。createNewFile
    public boolean createNewFile()
                          throws IOException当且仅当不存在具有此抽象路径名指定的名称的文件时,原子地创建由此抽象路径名指定的一个新的空文件。检查文件是否存在,如果不存在则创建该文件,这是单个操作,对于其他所有可能影响该文件的文件系统活动来说,该操作是原子的。 
    注:此方法不应 用于文件锁定,因为所得到的协议可能无法可靠地工作。应该使用 FileLock 机制替代。 
    返回:
    如果指定的文件不存在并成功地创建,则返回 true;如果指定的文件已经存在,则返回 false 
    抛出: 
    IOException - 如果发生 I/O 错误 
    SecurityException - 如果存在安全管理器,且其 SecurityManager.checkWrite(java.lang.String) 方法拒绝对文件进行写入访问
    从以下版本开始: 
    1.2