import java.io.*; 
class FileCons { 
  public static void main(String[] args) { 
  try{ 
    File f1 = new File("d:\\"); 
    File f2 = new File("d:\\","zhaozhao"); 
    File f3 = new File("f2","sss.txt"); 
    File f4 = new File("File1.java"); 
    File f5 = new File("asdf+?12/"); 
    if (f1.exists()) 
         System.out.println(f1 +" exists");
    else System.out.println(f1 +" is not exists");    
    System.out.println("Path of F1 is " + f1.getPath());
    
    if (f2.exists()) 
         System.out.println(f2 +" exists");  
    else System.out.println(f2 +" is not exists");
    /*从答案中我们可以看出d:\zhaozhao这个文件夹并不存在
    /*下面我们将创建文件夹zhaozhao*/
    f2.mkdir() ;
    if (f2.exists()) 
         System.out.println("After mkdir() , "+f2 +" exists");  
    else System.out.println(f2 +" is still not exists");
    
    
    if (f3.exists()) 
    
        System.out.println(f3 +" exists"); 
    else { System.out.println(f3 +"is not  exists"); /*由这句话我们知道f3.exits()
        没有抛出异常*/
          
        f3.createNewFile();
     /*d:\zhaozhao文件夹已经存在,为什么仍然无法在那个文件夹下创建文件sss.txt,
     *f3.createNewFile()抛出异常*/
        System.out.println("F3 was created!"); 
        } 
     if(f4.exists())
        { System.out.println(f4+"  exists,the AbsolutePath is  "+f4.getAbsolutePath());
          
          }
     else{
      f4.createNewFile();
      System.out.println("F4 was created!");
       }
       if(f5.exists())
         System.out.println(f5+"exists");
     else{
      f5.createNewFile();
      System.out.println("F5 was created!");
       }
   } catch(java.io.IOException e) { 
        e.printStackTrace(); 
    } 
  } 

     运行结果:
d:\ exit
Path of F1 is d:\
d:\zhaozhao exits
After mkdir(),d:\zhaozhao exists.
f2\sss.txtis not exists
java.io.IOException:系统找不到指定的路径。
       at java.io.WinNTFileSystem.createFileExclusively<Native Method>
       at java.io.File.createNewFile<File.java:828>
       at FileCons.main<FileCons4.java:32>疑惑:
下面是运行结果,我不明白d:\zhaozhao已经存在了,为什么 f3.createNewFile()会抛出异常,按理说应该建一个文件d:\zhaozhao\sss.txt?

解决方案 »

  1.   

    File f3 = new File("f2","sss.txt"); 
    这句是什么意思啊? \f2\sss.txt?System.out.println(f1 +" exists");
    这句真的能打印出来 “d:\ exit”吗?File f4 = new File("File1.java"); 
    这句应该把路径也加上File f5 = new File("asdf+?12/"); 
    这个路径名不合法你把程序跑一遍,改一改再贴上来吧
      

  2.   

    我找到问题的解决方法了
    File(File  parent, String  child) 
    根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
    File(String  pathname) 
    通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。
    File(String  parent, String  child) 
    根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
    File(URI  uri) 
    通过将给定的 file: URI 转换成一个抽象路径名来创建一个新的 File 实例。
    所以问题在于
    File f3 = new File("f2","sss.txt"); 
    应该是
    File f3=new  File(f2,  ”sss.txt”);其中File f4 = new File("File1.java");是正确的。是使用相对URI来创建一个File 对象引用。表示当前目录下的File.java文件引用
    至于File f5 = new File("asdf+?12/"); 文件名字不对