码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-01 18:08:08      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

                                                                            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类的基本内容

 

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

标签:

原文地址:http://www.cnblogs.com/Seffrui/p/5010744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!