Java IO流學習總結二:File

轉載請標明出處:http://blog.csdn.net/zhaoyanjun6/article/details/54581478
本文出自【趙彥軍的博客】java

Java File類的功能很是強大,利用java基本上能夠對文件進行全部操做。
首先來看File類的構造函數的源碼windows

/**
     * Internal constructor for already-normalized pathname strings.
     */
  private File(String pathname, int prefixLength) {
        this.path = pathname;
        this.prefixLength = prefixLength;
    }

    /**
     * Internal constructor for already-normalized pathname strings.
     * The parameter order is used to disambiguate this method from the
     * public(File, String) constructor.
     */
    private File(String child, File parent) {
        assert parent.path != null;
        assert (!parent.path.equals(""));
        this.path = fs.resolve(parent.path, child);
        this.prefixLength = parent.prefixLength;
    }

    /**
     * Creates a new <code>File</code> instance by converting the given
     * pathname string into an abstract pathname.  If the given string is
     * the empty string, then the result is the empty abstract pathname.
     *
     * @param   pathname  A pathname string
     * @throws  NullPointerException
     *          If the <code>pathname</code> argument is <code>null</code>
     */
    public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

 
     /**
     * @param   parent  The parent pathname string
     * @param   child   The child pathname string
     * @throws  NullPointerException
     *          If <code>child</code> is <code>null</code>
     */
    public File(String parent, String child) {
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null && !parent.isEmpty()) {
            this.path = fs.resolve(fs.normalize(parent),
                                   fs.normalize(child));
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

    /**
     * @param   parent  The parent abstract pathname
     * @param   child   The child pathname string
     * @throws  NullPointerException
     *          If <code>child</code> is <code>null</code>
     */
    public File(File parent, String child) {
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null) {
            if (parent.path.equals("")) {
                this.path = fs.resolve(fs.getDefaultParent(),
                                       fs.normalize(child));
            } else {
                this.path = fs.resolve(parent.path,
                                       fs.normalize(child));
            }
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

    /**
     * @param  uri
     *         An absolute, hierarchical URI with a scheme equal to
     *         <tt>"file"</tt>, a non-empty path component, and undefined
     *         authority, query, and fragment components
     *
     * @throws  NullPointerException
     *          If <tt>uri</tt> is <tt>null</tt>
     *
     * @throws  IllegalArgumentException
     *          If the preconditions on the parameter do not hold
     */
    public File(URI uri) {

        // Check our many preconditions
        if (!uri.isAbsolute())
            throw new IllegalArgumentException("URI is not absolute");
        if (uri.isOpaque())
            throw new IllegalArgumentException("URI is not hierarchical");
        String scheme = uri.getScheme();
        if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
            throw new IllegalArgumentException("URI scheme is not \"file\"");
        if (uri.getAuthority() != null)
            throw new IllegalArgumentException("URI has an authority component");
        if (uri.getFragment() != null)
            throw new IllegalArgumentException("URI has a fragment component");
        if (uri.getQuery() != null)
            throw new IllegalArgumentException("URI has a query component");
        String p = uri.getPath();
        if (p.equals(""))
            throw new IllegalArgumentException("URI path component is empty");

        // Okay, now initialize
        p = fs.fromURIPath(p);
        if (File.separatorChar != '/')
            p = p.replace('/', File.separatorChar);
        this.path = fs.normalize(p);
        this.prefixLength = fs.prefixLength(this.path);
    }

從源碼能夠看出File類的構造函數有6個,精簡以下數組

public File(String pathname)  //文件的絕對路徑
public File(URI uri)  //文件的URI地址

public File(String parent, String child)  //指定父文件絕對路徑、子文件絕對路徑
public File(File parent, String child)  //指定父文件、子文件相對路徑


//下面這兩個是File類中私有的構造函數,外面不能調用
private File(String child, File parent)  
private File(String pathname, int prefixLength)

如今就看的比較清楚了,6個構造函數,能夠分爲2類。4個公共構造函數,2個私有構造函數。app

構造函數1:ide

//電腦d盤中的cat.png 圖片的路徑
String filePath1 = "D:/cat.png" ;
File file = new File( filePath1 ) ;

構造函數2:函數

String parentFilePath = "E:/cat" ;
        
String childFilePath = "small_cat.txt" ;

//建立parentFile文件
File parentFile = new File( parentFilePath ) ;
parentFile.mkdir() ;
        
//若是parentFile不存在,就會報異常
File file = new File( parentFilePath  , childFilePath ) ;
    
try {
    file.createNewFile() ;
} catch (IOException e) {
    e.printStackTrace();
}

效果圖:
this

構造函數3:.net

String parentFilePath = "E:/cat" ;

//構造父文件
File parent = new File( parentFilePath ) ;
parent.mkdir(); 

//若是parent文件不存在,就會報異常
File file = new File( parent  , "small_cat.txt" ) ;
    
try {
    file.createNewFile() ;
} catch (IOException e) {
    e.printStackTrace();
}

效果圖:
code

  • 建立目錄
boolean  file.mkdir()

若是建立成功,返回 true , 建立失敗,返回false。若是這個文件夾已經存在,則返回false.
只能建立一級目錄,若是父目錄不存在,返回false.component

  • 建立多級目錄
boolean  file.mkdirs()

建立多級目錄,建立成功,返回true,建立失敗,返回false。若是父目錄不存在,就建立,而且返回true.

  • 建立一個新的文件
boolean file.createNewFile() ;

若是文件不存在就建立該文件,建立成功,返回 true ;建立失敗,返回false。若是這個文件已經存在,則返回false.

  • 判斷方法
boolean file.exists() //文件是否存在

boolean file.isFile() //是不是文件

boolean file.isDirectory() //是不是目錄

boolean file.isHidden()   //是否隱藏(windows上能夠設置某個文件是否隱藏)

boolean file.isAbsolute() //是否爲絕對路徑

boolean file.canRead()  //是否可讀

boolean file.canWrite() //是否可寫

boolean file.canExecute()  //是否可執行

獲取文件的信息

String file.getName() //獲取文件的名字,只是名字,沒有路徑

String file.getParent() //獲取父目錄的絕對路徑,返回值是一個字符串。若是文件有父目錄,那麼返回父目錄的絕對路徑,(好比:`E:\cat`) , 若是文件自己就在磁盤的根目錄,那麼返回磁盤的路徑,(好比:`E:\`)。

File file.getParentFile() //獲取父文件,返回值是一個File對象。

long time = file.lastModified() ; //返回文件最後一次修改的時間
Date dt = new Date(time);

boolean renameTo(File file) //文件命名

long file.length() //返回文件的大小,單位字節

boolean file.delete() //刪除文件

String[] file.list() //獲取該目錄下的全部的文件的名字。若是`file`爲文件,返回值爲`null`,在使用時記得判空;可是若是`file`爲目錄,那麼返回這個目錄下全部文件的名字,只是名字,不含路徑;若是`file`是一個空目錄,返回一個長度爲0的數組;從上面的結果能夠看出,`list()` 方法,只是對`file`爲目錄時有效,當`file`爲一個文件的時候,該方法毫無心義。

File[] file.listFiles() //獲取該目錄下的全部的文件。若是`file`爲文件,返回值爲`null`,在使用時記得判空;可是若是`file`爲目錄,那麼返回這個目錄下全部的文件 ;若是`file`是一個空目錄,返回一個長度爲0的數組;從上面的結果能夠看出,`listFiles()` 方法,只是對`file`爲目錄時有效,當`file`爲一個文件的時候,該方法毫無心義。

實戰經驗1: file.list() , file.listFiles()

String filePath = "E:/cat" ;
File file = new File( filePath ) ;
file.mkdir() ;

String[] names = file.list() ;

for( int i = 0 ; i < names.length ; i++ ){
    System.out.println( "names: " +names[i]);
}

File[] files = file.listFiles() ;
for( int i = 0 ; i < files.length ; i++ ){
    System.out.println( "files: "+ files[i].getAbsolutePath() );
}

效果圖:

實戰經驗2:掃描F盤全部的文件

public class A3 {

    public static void main(String[] args) throws IOException {

        String filePath = "F:/" ;
        File file = new File( filePath ) ;
        getFile(file);

    }


    private static void getFile( File file ){
        File[] files = file.listFiles() ;
        for( File f : files ){
            if ( f.isHidden() ) continue ;

            if(f.isDirectory() ){
                getFile( f );               
            }else{
                System.out.println( f.getAbsolutePath()  + "  " + f.getName() );
            }
        }
    }
}

效果圖:

這裏寫圖片描述

在上面的實戰演練中用到了,file.list() , file.listFiles() 。這是兩個無參的方法,實際上還有兩個有參的方法,分別是

file.list(FilenameFilter filter) ;

file.listFiles( FilenameFilter filter) ;

file.listFiles(FileFilter filter)

FileFilter

FileFilter是io包裏面的一個接口,從名字上能夠看出,這個類是文件過濾功能的。
須要重寫accept方法
好比:

static class MyFileFilter implements FileFilter {
        
MyFileFilter(){         
}
        
//pathname:文件的絕對路徑+ 文件名 , 好比:F:\安來寧 - 可貴.mp3  , 或者: F:\文件夾1
@Override
public boolean accept(File pathname) {
    return false;
}   
}

實戰:獲取指定目錄的全部文件夾

package com.app;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;


public class A3 {

    public static void main(String[] args) throws IOException {

        String filePath = "F:/" ;
        File file = new File( filePath ) ;
        getFile(file);

    }


    /**
     * 獲取指定目錄的全部文件夾
     * @param file
     */
    private static void getFile( File file ){
        MyFileFilter myFileFilter = new MyFileFilter() ;

        File[] files = file.listFiles( myFileFilter ) ;
        for( File f : files ){
            if ( f.isHidden() ) continue ;

            System.out.println( f.getAbsolutePath() );
        }
    }


    static class MyFileFilter implements FileFilter {

        MyFileFilter(){

        }

        //pathname:文件的絕對路徑+ 文件名 , 好比:F:\安來寧 - 可貴.mp3  , 或者: F:\文件夾1
        @Override
        public boolean accept(File pathname) {
            if( pathname.isDirectory() ){
                return true ;
            }
            return false;
        }

    }

}

FilenameFilter

FileFilter是io包裏面的一個接口,從名字上能夠看出,這個類是文件名字過濾功能的。
須要重寫裏面的accept方法。
好比:

package com.app;

import java.io.File;
import java.io.FilenameFilter;

public class MyFilenameFilter implements FilenameFilter {
    //type爲須要過濾的條件,好比若是type=".jpg",則只能返回後綴爲jpg的文件
    private String type;           
    MyFilenameFilter( String type){
        this.type = type ;
    }

    @Override
    public boolean accept(File dir, String name) {
        //dir表示文件的當前目錄,name表示文件名;
        return name.endsWith( type ) ;
    }

}

實戰:掃描出指定路徑的全部圖片

package com.app;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;


public class A3 {

    public static void main(String[] args) throws IOException {

        String filePath = "F:/" ;
        File file = new File( filePath ) ;
        getFile(file);

    }


    /**
     * 掃描出指定路徑的全部圖片
     * @param file
     */
    private static void getFile( File file ){
        MyFilenameFilter myFileFilter = new MyFilenameFilter( ".png") ;

        File[] files = file.listFiles( myFileFilter ) ;
        for( File f : files ){
            if ( f.isHidden() ) continue ;

            System.out.println( f.getAbsolutePath() );
        }
    }



    static class MyFilenameFilter implements FilenameFilter {
        //type爲須要過濾的條件,好比若是type=".jpg",則只能返回後綴爲jpg的文件
        private String type;           
        MyFilenameFilter( String type){
            this.type = type ;
        }

        @Override
        public boolean accept(File dir, String name) {
            //dir表示文件的當前目錄,name表示文件名;
            return name.endsWith( type ) ;
        }

    }

}

運行結果:
這裏寫圖片描述

相關文章
相關標籤/搜索