Java 学习计划 11月28日-12月1日

                                                                            File类基本操作

   在Linux中,一切皆文件,所以文件操作是基础。

   Java中提供File类来提供一些对文件的基本操作,面对一个新类,第一件事就是去看API文档

   File类的API文档中对于文件的路径进行了说明 Linux或Unix下用'/' windows下用‘\';

   在API的最后一行,有一句说明,

   Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

   就是说一个File一旦实例化 就不可以在指向其他文件。只能在此实例化一个File来打开该文件

 

 

   下面是一些File类的基本操作。

   

public class FileDemo {
    public static void main(String[] args) {
                //构造函数
        File file = new File("G:\\text.txt");
        //判断文件或目录是否存在
        if(!file.exists())
            file.mkdir(); //file.mkdirs()
        else
            file.delete();
        //是否是一个目录  如果是目录返回true,如果不是目录or目录不存在返回的是false
        System.out.println(file.isDirectory());
        //是否是一个文件
        System.out.println(file.isFile());
        
    //另一个构造函数
        File file2 = new File("G:\\","test1.txt");
        if(!file2.exists())
            try {
                file2.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        else 
            file2.delete();
         //常用的File对象的API
        System.out.println(file);//file.toString()的内容
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getName());
        System.out.println(file2.getName());
        System.out.println(file.getParent());
        System.out.println(file2.getParent());
        System.out.println(file.getParentFile().getAbsolutePath());
    }

}
    

 获取一个目录下的所有文件

 

public void showDirectory(File dir)
{
     //判断dir是否是目录
     if(!dir.exits() || !dir.isDirectory())
     {
          throw new Exception(dir+"不是目录");
     } 
     //遍历目录
     File[]  files=dir.listFiles();
     for(File file : files)
        {
             if(file.isDirectory())
                showDirectory(file);
             else
                 System.out.println(file.getAbsolutePath());
        }
}        

 以上就是File类的基本内容

 在Linux中经常需要创建临时文件来提供临时的存储,在程序结束时自动删除该文件,File类提供了一个创建临时文件的方法

        File file= null;
        try {
            file = File.createTempFile("text", ".txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(file);

但是输出结果并不是想要的 text.txt

 

看了下文档

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:

  1. The file denoted by the returned abstract pathname did not exist before this method was invoked, and
  2. Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

他是用前缀和后缀来生成文件名 而不是前缀+后缀,来保证每个临时文件都是唯一的

posted @ 2015-12-01 17:27  Seffrui  阅读(179)  评论(0)    收藏  举报