源码:File file=new File ("d:/work/newtemp.txt");
System.out.println(file.getName());
编译通过,也能输出文件名。。
但是为嘛d盘上没有这个txt文件。。目录也没有。。
用File.separator也试过。还是木有
高手求助。

解决方案 »

  1.   

    你看下jdk的源码就知道了.
    比如File.getParent()这个只是根据当前的路径,截断File.separator这个,将前面的String返回的.
    不会去判断此文件是否存在.这个getName()就是将path返回而已. public String getName() {
    int index = path.lastIndexOf(separatorChar);
    if (index < prefixLength) return path.substring(prefixLength);
    return path.substring(index + 1);
        }
      

  2.   

    你必须正确地理解File类型的对象
    它不一定是代表一个硬盘上已经存在的文件
    它也可能代表一个还不存在但你准备创建的文件
    当然,它也可能是一个目录
    理解了这些就能明白
    new File(filename)
    只是内存中的一个文件对象,它可能已经存在,也可能还未创建
    如果你下一步往里面写入东西,这个文件就在硬盘上创建了。
      

  3.   

    createNewFile
    public boolean createNewFile() throws IOException
    Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file. 
      

  4.   


    package com.ex;import java.io.File;
    import java.io.IOException;
    public class Test { /**
     * @param args
     */
    public static void main(String[] args) {
    File file=new File ("d:/work/newtemp.txt");
    String str = file.getAbsolutePath() ;
    String sDir = str.replaceAll(file.getName(), "") ; //得到所在目录
                       File dir = new File(sDir) ;
            if (! dir.exists() ){ //判断目录是否存在,如果不存在就创建 ;
             dir.mkdirs() ; //mkdirs()可以创建多级目录 
            }
            
    if (! file.exists()){ //判断文件是否存在 
         try {
    file.createNewFile() ; //创建文件
    } catch (IOException e) {
    e.printStackTrace();
    }
        } System.out.println(file.getName()); }}