天天看點

Java IO流學習總結二:File

轉載請标明出處:http://blog.csdn.net/zhaoyanjun6/article/details/54581478

本文出自【趙彥軍的部落格】

Java File類的功能非常強大,利用java基本上可以對檔案進行所有操作。

首先來看File類的構造函數的源碼

/**
     * 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個私有構造函數。

構造函數1:

//電腦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();
}

           

效果圖:

構造函數3:

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();
}

           
  • 建立目錄
boolean  file.mkdir()
           

如果建立成功,傳回

true

, 建立失敗,傳回

false

。如果這個檔案夾已經存在,則傳回

false

.

隻能建立一級目錄,如果父目錄不存在,傳回

false

  • 建立多級目錄
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 ) ;
		}

	}

}

           

運作結果: