Java--File文件操作
判斷文件或目錄是否存在
判斷File對象所指向的文件或者目錄是否存在,使用exists()函數(shù)。
File f = new File("/Users/bemaster/Desktop/in.txt"); System.out.println(f.exists());?
?
判斷當前File對象是文件還是目錄
判斷當前File對象是否是文件,使用isFile()函數(shù)。
判斷當前File對象是否是目錄,使用isDirectory()函數(shù)。
File f = new File("/Users/bemaster/Desktop/in.txt"); File f2 = new File("/Users/bemaster/Desktop/in.txt"); if(f.isFile())System.out.println("is file!!!"); if(f2.isDirectory())System.out.println("is directory!!!");?
?
新建文件或目錄
新建文件,使用createNewFile()函數(shù)
File f = new File("/Users/bemaster/Desktop/in.txt"); try {if(!f.exists())f.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }?
新建目錄,使用mkdir()或者mkdirs()函數(shù)。區(qū)別是前者是新建單級目錄,而后者是新建多級目錄。
即如果新建目錄時,如果上一級目錄不存在,那么mkdir()是不會執(zhí)行成功的。
/*如果User目錄,或者bemaster目錄,或者Desktop目錄不存在, * 如果使用mkdir(),則新建tmp目錄失敗 * 如果使用mkdirs(),則連不存在的上級目錄一起新建 */ File f = new File("/Users/bemaster/Desktop/tmp"); if(!f.exists())f.mkdir();?
?
獲取當前目錄下的所有文件
list()函數(shù)返回當前目錄下所有文件或者目錄的名字(即相對路徑)。
listFiles()函數(shù)返回當前目錄下所有文件或者目錄的File對象。
很顯然,list()函數(shù)效率比較高,因為相比于listFiles()函數(shù)少了一步包裝成File對象的步驟。
上面的兩個函數(shù)都有另外一個版本,可以接受一個過濾器,即返回那么滿足過濾器要求的。
public String[] list(); public String[] list(FilenameFilter filter); public File[] listFiles(); public File[] listFiles(FileFilter filter); public File[] listFiles(FilenameFilter filter);?
?
刪除文件或目錄
刪除文件或目錄都是使用delete(),或者deleteOnExit()函數(shù),但是如果目錄不為空,則會刪除失敗。
delete()和deleteOnExit()的區(qū)別是前者立即刪除,而后者是等待虛擬機退出時才刪除。
File f = new File("/Users/bemaster/Desktop/in.txt"); f.delete();如果想要刪除非空的目錄,則要寫個函數(shù)遞歸刪除。
/*** *<刪除文件或者目錄,如果目錄不為空,則遞歸刪除* @param file filepath 你想刪除的文件* @throws FileNotFoundException 如果文件不存在,拋出異常* */public static void delete(File file) throws FileNotFoundException {if(file.exists()){File []fileList=null;//如果是目錄,則遞歸刪除該目錄下的所有東西if(file.isDirectory() && (fileList=file.listFiles()).length!=0){for(File f:fileList)delete(f);}//現(xiàn)在可以當前目錄或者文件了 file.delete();}else{throw new FileNotFoundException(file.getAbsolutePath() + "is not exists!!!");}}?
?
重命名(移動)文件或目錄
重命名文件或目錄是使用renameTo(File)函數(shù),如果想要移動文件或者目錄,只需要改變其路徑就可以做到。
File f = new File("/Users/bemaster/Desktop/in.txt"); f.renameTo(new File("/Users/bemaster/Desktop/in2.txt"));?
?
復制文件或目錄
File類不提供拷貝文件或者對象的函數(shù),所以需要自己實現(xiàn)。
/*** through output write the byte data which read from input * 將從input處讀取的字節(jié)數(shù)據(jù)通過output寫到文件* @param input* @param output* @throws IOException*/private static void copyfile1(InputStream input, OutputStream output) {byte[] buf = new byte[1024];int len;try {while((len=input.read(buf))!=-1){output.write(buf, 0, len);}} catch (IOException e) {e.printStackTrace();}finally{try {input.close();output.close();} catch (IOException e) {e.printStackTrace();}}}public static void copyFile(String src, String des, boolean overlay) throws FileNotFoundException{copyFile(new File(src), new File(des), overlay);}/*** * @param src 源文件* @param des 目標文件* @throws FileNotFoundException */public static void copyFile(File src, File des, boolean overlay) throws FileNotFoundException {FileInputStream fis = null;FileOutputStream fos = null;BufferedInputStream bis = null;BufferedOutputStream bos = null;if(src.exists()){try {fis = new FileInputStream(src);bis = new BufferedInputStream(fis);boolean canCopy = false;//是否能夠寫到desif(!des.exists()){des.createNewFile();canCopy = true;}else if(overlay){canCopy = true;}if(canCopy){fos = new FileOutputStream(des);bos = new BufferedOutputStream(fos);copyfile1(bis, bos);}} catch (FileNotFoundException e) {// TODO Auto-generated catch block e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}}else{throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");}}public static void copyDirectory(String src, String des) throws FileNotFoundException{copyDirectory(new File(src), new File(des));}public static void copyDirectory(File src, File des) throws FileNotFoundException{if(src.exists()){if(!des.exists()){des.mkdirs();}File[] fileList = src.listFiles();for(File file:fileList){//如果是目錄則遞歸處理if(file.isDirectory()){copyDirectory(file, new File(des.getAbsolutePath()+"/"+file.getName()));}else{//如果是文件,則直接拷貝copyFile(file, new File(des.getAbsolutePath()+"/"+file.getName()), true);}}}else{throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");}}?
?
獲得當前File對象的絕對路徑和名字
File f = new File("/Users/bemaster/Desktop/in.txt"); //輸出絕對路徑, 即/Users/bemaster/Desktop/in.txt System.out.println(f.getAbsolutePath()); //輸出父目錄路徑, 即/Users/bemaster/Desktop/ System.out.println(f.getParent()); //輸出當然文件或者目錄的名字, 即in.txt System.out.println(f.getName());?
?
統(tǒng)計文件或者目錄大小
獲得文件的大小可以使用length()函數(shù)。 File f = new File("/Users/bemaster/Desktop/in.txt"); System.out.println(f.length());?
如果對目錄使用length()函數(shù),可能會返回錯誤的結果,所以只好自己寫個函數(shù)遞歸統(tǒng)計其包含的文件的大小。
private static long getTotalLength1(File file){long cnt = 0;if(file.isDirectory()){File[] filelist = file.listFiles();for(File f : filelist){cnt += getTotalLength1(f);}}else{cnt += file.length();}return cnt;}public static long getTotalLength(String filepath) throws FileNotFoundException{return getTotalLength(new File(filepath));}public static long getTotalLength(File file) throws FileNotFoundException{if(file.exists()){return getTotalLength1(file);}else{throw new FileNotFoundException(file.getAbsolutePath()+" not found!!!");}}?
?
其它函數(shù)
File類所提供的函數(shù)當前不止這些,還有一些操作,比如獲得文件是否可讀,可寫,可操作;設置文件可讀,可寫,可操作等等。
?
FileUtil工具類
下面是自己寫的FileUtil工具類。
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket;/*** * @author bemaster;* @category 文件工具類,包含了基本的文件操作* @version 1.0* */public class FileUtil {private static final long B = 1;private static final long K = B<<10;private static final long M = K<<10;private static final long G = M<<10;private static final long T = G<<10;/*** *刪除文件或者目錄,如果目錄不為空,則遞歸刪除* @param filepath 你想刪除的文件的路徑* @throws FileNotFoundException 如果該路徑所對應的文件不存在,拋出異常* */public static void delete(String filepath) throws FileNotFoundException{File file = new File(filepath);delete(file);}/*** *<刪除文件或者目錄,如果目錄不為空,則遞歸刪除* @param file filepath 你想刪除的文件* @throws FileNotFoundException 如果文件不存在,拋出異常* */public static void delete(File file) throws FileNotFoundException {if(file.exists()){File []fileList=null;//如果是目錄,則遞歸刪除該目錄下的所有東西if(file.isDirectory() && (fileList=file.listFiles()).length!=0){for(File f:fileList)delete(f);}//現(xiàn)在可以當前目錄或者文件了 file.delete();}else{throw new FileNotFoundException(file.getAbsolutePath() + "is not exists!!!");}}/*** through output write the byte data which read from input * 將從input處讀取的字節(jié)數(shù)據(jù)通過output寫到文件* @param input* @param output* @throws IOException*/private static void copyfile1(InputStream input, OutputStream output) {byte[] buf = new byte[1024];int len;try {while((len=input.read(buf))!=-1){output.write(buf, 0, len);}} catch (IOException e) {e.printStackTrace();}finally{try {input.close();output.close();} catch (IOException e) {e.printStackTrace();}}}public static void copyFile(String src, String des, boolean overlay) throws FileNotFoundException{copyFile(new File(src), new File(des), overlay);}/*** * @param src 源文件* @param des 目標文件* @throws FileNotFoundException */public static void copyFile(File src, File des, boolean overlay) throws FileNotFoundException {FileInputStream fis = null;FileOutputStream fos = null;BufferedInputStream bis = null;BufferedOutputStream bos = null;if(src.exists()){try {fis = new FileInputStream(src);bis = new BufferedInputStream(fis);boolean canCopy = false;//是否能夠寫到desif(!des.exists()){des.createNewFile();canCopy = true;}else if(overlay){canCopy = true;}if(canCopy){fos = new FileOutputStream(des);bos = new BufferedOutputStream(fos);copyfile1(bis, bos);}} catch (FileNotFoundException e) {// TODO Auto-generated catch block e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}}else{throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");}}public static void copyDirectory(String src, String des) throws FileNotFoundException{copyDirectory(new File(src), new File(des));}public static void copyDirectory(File src, File des) throws FileNotFoundException{if(src.exists()){if(!des.exists()){des.mkdirs();}File[] fileList = src.listFiles();for(File file:fileList){//如果是目錄則遞歸處理if(file.isDirectory()){copyDirectory(file, new File(des.getAbsolutePath()+"/"+file.getName()));}else{//如果是文件,則直接拷貝copyFile(file, new File(des.getAbsolutePath()+"/"+file.getName()), true);}}}else{throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");}}public static String toUnits(long length){String sizeString = "";if(length<0){length = 0;}if(length>=T){sizeString = sizeString + length / T + "T" ;length %= T;}if(length>=G){sizeString = sizeString + length / G + "G" ;length %= G;}if(length>=M){sizeString = sizeString + length / M + "M";length %= M;}if(length>=K){sizeString = sizeString + length / K+ "K";length %= K;}if(length>=B){sizeString = sizeString + length / B+ "B";length %= B;}return sizeString; }private static long getTotalLength1(File file){long cnt = 0;if(file.isDirectory()){File[] filelist = file.listFiles();for(File f : filelist){cnt += getTotalLength1(f);}}else{cnt += file.length();}return cnt;}public static long getTotalLength(String filepath) throws FileNotFoundException{return getTotalLength(new File(filepath));}public static long getTotalLength(File file) throws FileNotFoundException{if(file.exists()){return getTotalLength1(file);}else{throw new FileNotFoundException(file.getAbsolutePath()+" not found!!!");}} }?
轉載于:https://www.cnblogs.com/justPassBy/p/5342436.html
總結
以上是生活随笔為你收集整理的Java--File文件操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ThinkPHP---RBAC
- 下一篇: request.get... getHe