-------------------File的使用--------------
1.File類對文件的處理
1.1目錄結構:
1.2測試對文件Test.txt處理:
// 測試文件 @Test public void test1() throws IOException { String contextPath = System.getProperty("user.dir");// 獲取項目名字 System.out.println("文件路徑: " + contextPath + "/Test.txt"); // 創建File的第一種方式 // File file = new File(contextPath + "/Test.txt"); // 第二種方式 File file = new File(contextPath, "/Test.txt"); // 判斷文件是否存在,如果不存在就新創文件 if (!file.exists()) { // file.delete();刪除文件 file.createNewFile();// 創建一個Text.txt文件 System.out.println("新增文件"); } System.out.println("是否是文件" + file.isFile()); System.out.println("是否是目錄" + file.isDirectory()); // 獲取文件大小(以字節為單位) if (file.isFile()) { System.out.println("文件大小:" + file.length() + "字節"); } System.out.println("此文件的上級目錄是" + file.getParent()); }
結果:
文件路徑: E:\EclipseWorkspace\AllTest/Test.txt
是否是文件true
是否是目錄false
文件大小:40字節
此文件的上級目錄是E:\EclipseWorkspace\AllTest
2.對目錄的處理
2.1目錄結構:
2.2測試代碼:
// 測試目錄 @Test public void test2() throws IOException { String contextPath = System.getProperty("user.dir");// 獲取項目名字 System.out.println("文件路徑: " + contextPath + "\\text"); // 第一種方式 // File file = new File(contextPath,"text"); // 第二種 File file = new File(contextPath, "text"); System.out.println("文件是否存在" + file.exists()); if (!file.exists()) {// 如果目錄不存在 file.mkdir();// 創建目錄 } // 判斷文件是否存在,如果存在刪除文件 System.out.println("是否是文件" + file.isFile()); System.out.println("是否是目錄" + file.isDirectory()); // 列舉目錄下的文件的名字 if (file.isDirectory()) { File[] listFiles = file.listFiles(); System.out.println("目錄下的文件有:"); for (File fi : listFiles) { // 列舉文件名字與大小 System.out.println(fi.getName() + " 大小 " + fi.length() * 1.0 / 1024 + "KB"); // 刪除文件 System.out.println("文件將被刪除"); fi.delete(); } } System.out.println("此文件的上級目錄是" + file.getParent()); }
結果:
文件路徑: E:\EclipseWorkspace\AllTest\text 文件是否存在true 是否是文件false 是否是目錄true 目錄下的文件有: 1.txt 大小 0.015625KB 文件將被刪除 9.20PDM截圖.pdf 大小 193.109375KB 文件將被刪除 web.xml 大小 0.951171875KB 文件將被刪除 此文件的上級目錄是E:\EclipseWorkspace\AllTest
總結:如果刪除一個目錄下的文件可以用上述的辦法遍歷一個目錄下的文件然后刪除文件。
-------------------FileUtils\Filenameutils\IOUtils的使用(commons-io.jar)--------------
需要注意的是tomcat的包下也有一個這個類,注意用的是commons-io的包,不要用錯:
參考:http://langgufu.iteye.com/blog/2215918
分類說明演示:
1.寫 文件/文件夾
2.讀 文件/文件夾
3.刪除 文件/文件夾
4.移動 文件/文件夾
5.copy
6.其他
7.FilenameUtils可以對文件的名字進行處理,可以快速的獲取文件的擴展名與基本名字:(commons-io.jar)
補充:
8.IOUtils實現文件拷貝
org.apache.commons.io.IOUtils可以簡單的將一個inputStream的文件讀取到另一個outputStream,實現文件的拷貝,例如:
只用傳兩個參數,第一個傳遞InputStream,第二個傳遞OutputStream
package cn.qlq.craw.Jsoup; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import org.apache.commons.io.IOUtils; public class IOutilsDownloadFile { public static void main(String[] args) throws IOException { String url = "http://qiaoliqiang.cn/fileDown/zfb.bmp"; URL url1 = new URL(url); URLConnection conn = url1.openConnection(); InputStream inputStream = conn.getInputStream(); String path = "C:\\Users\\liqiang\\Desktop\\test.bmp"; OutputStream outputStream = new FileOutputStream(path); // 利用IOutiks拷貝文件,簡單快捷 IOUtils.copy(inputStream, outputStream); } }
其內部也是通過in.read讀出內容之后,寫入到output:
private static final int EOF = -1; private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } public static long copyLarge(InputStream input, OutputStream output) throws IOException { return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]); } public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { long count = 0; int n = 0; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; }
IOUtils可以用來在finally中關閉流:(無條件的關閉而不拋出異常)
public void exportExcel(OutputStream outputStream) { // 導出之前先自動設置列寬 this.autoAllSizeColumn(); try { workBook.write(outputStream); } catch (IOException e) { LOGGER.error(" exportExcel error", e); } finally { IOUtils.closeQuietly(outputStream); } }
查看源碼:
/** * Unconditionally close an <code>OutputStream</code>. * <p> * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. * <p> * Example code: * <pre> * byte[] data = "Hello, World".getBytes(); * * OutputStream out = null; * try { * out = new FileOutputStream("foo.txt"); * out.write(data); * out.close(); //close errors are handled * } catch (IOException e) { * // error handling * } finally { * IOUtils.closeQuietly(out); * } * </pre> * * @param output the OutputStream to close, may be null or already closed */ public static void closeQuietly(OutputStream output) { closeQuietly((Closeable)output); }
/** * Unconditionally close a <code>Closeable</code>. * <p> * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. * <p> * Example code: * <pre> * Closeable closeable = null; * try { * closeable = new FileReader("foo.txt"); * // process closeable * closeable.close(); * } catch (Exception e) { * // error handling * } finally { * IOUtils.closeQuietly(closeable); * } * </pre> * * @param closeable the object to close, may be null or already closed * @since 2.0 */ public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } }