Q1:第一個輸入輸出流封裝類
package com.io1; import java.io.*; import java.net.MalformedURLException; import java.net.URL; /** * 文件工具類 */ public class FileUtil { /** * 讀取文件內容 * * @param is * @return */ public static String readFile(InputStream is) { BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String readLine = null; while ((readLine = br.readLine()) != null) { sb.append(readLine+"\r\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } /** * @description 寫文件 * @param args * @throws UnsupportedEncodingException * @throws IOException */ public static boolean writeTxtFile(String content, File fileName, String encoding) { FileOutputStream o = null; boolean result=false; try { o = new FileOutputStream(fileName); o.write(content.getBytes(encoding)); result=true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (o != null) { try { o.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static String readFile(String path){ File file07 = new File(path); InputStream is=null; try { is = new FileInputStream(file07); } catch (FileNotFoundException e) { e.printStackTrace(); } return readFile(is); } /** * 判斷指定的文件是否存在。 * * @param fileName * @return */ public static boolean isFileExist(String fileName) { return new File(fileName).isFile(); } /** * 創建指定的目錄。 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。 * 注意:可能會在返回false的時候創建部分父目錄。 * * @param file * @return */ public static boolean makeDirectory(File file) { File parent = file.getParentFile(); if (parent != null) { return parent.mkdirs(); } return false; } /** * 返回文件的URL地址。 * * @param file * @return * @throws MalformedURLException */ public static URL getURL(File file) throws MalformedURLException { String fileURL = "file:/" + file.getAbsolutePath(); URL url = new URL(fileURL); return url; } /** * 從文件路徑得到文件名。 * * @param filePath * @return */ public static String getFileName(String filePath) { File file = new File(filePath); return file.getName(); } /** * 從文件名得到文件絕對路徑。 * * @param fileName * @return */ public static String getFilePath(String fileName) { File file = new File(fileName); return file.getAbsolutePath(); } /** * 將DOS/Windows格式的路徑轉換為UNIX/Linux格式的路徑。 * * @param filePath * @return */ public static String toUNIXpath(String filePath) { return filePath.replace("", "/"); } /** * 從文件名得到UNIX風格的文件絕對路徑。 * * @param fileName * @return */ public static String getUNIXfilePath(String fileName) { File file = new File(fileName); return toUNIXpath(file.getAbsolutePath()); } /** * 得到文件后綴名 * * @param fileName * @return */ public static String getFileExt(String fileName) { int point = fileName.lastIndexOf('.'); int length = fileName.length(); if (point == -1 || point == length - 1) { return ""; } else { return fileName.substring(point + 1, length); } } /** * 得到文件的名字部分。 實際上就是路徑中的最后一個路徑分隔符后的部分。 * * @param fileName * @return */ public static String getNamePart(String fileName) { int point = getPathLastIndex(fileName); int length = fileName.length(); if (point == -1) { return fileName; } else if (point == length - 1) { int secondPoint = getPathLastIndex(fileName, point - 1); if (secondPoint == -1) { if (length == 1) { return fileName; } else { return fileName.substring(0, point); } } else { return fileName.substring(secondPoint + 1, point); } } else { return fileName.substring(point + 1); } } /** * 得到文件名中的父路徑部分。 對兩種路徑分隔符都有效。 不存在時返回""。 * 如果文件名是以路徑分隔符結尾的則不考慮該分隔符,例如"/path/"返回""。 * * @param fileName * @return */ public static String getPathPart(String fileName) { int point = getPathLastIndex(fileName); int length = fileName.length(); if (point == -1) { return ""; } else if (point == length - 1) { int secondPoint = getPathLastIndex(fileName, point - 1); if (secondPoint == -1) { return ""; } else { return fileName.substring(0, secondPoint); } } else { return fileName.substring(0, point); } } /** * 得到路徑分隔符在文件路徑中最后出現的位置。 對於DOS或者UNIX風格的分隔符都可以。 * * @param fileName * @return */ public static int getPathLastIndex(String fileName) { int point = fileName.lastIndexOf("/"); if (point == -1) { point = fileName.lastIndexOf(""); } return point; } /** * 得到路徑分隔符在文件路徑中指定位置前最后出現的位置。 對於DOS或者UNIX風格的分隔符都可以。 * * @param fileName * @param fromIndex * @return */ public static int getPathLastIndex(String fileName, int fromIndex) { int point = fileName.lastIndexOf("/", fromIndex); if (point == -1) { point = fileName.lastIndexOf("", fromIndex); } return point; } /** * 得到路徑分隔符在文件路徑中首次出現的位置。 對於DOS或者UNIX風格的分隔符都可以。 * * @param fileName * @return */ public static int getPathIndex(String fileName) { int point = fileName.indexOf("/"); if (point == -1) { point = fileName.indexOf(""); } return point; } /** * 得到路徑分隔符在文件路徑中指定位置后首次出現的位置。 對於DOS或者UNIX風格的分隔符都可以。 * * @param fileName * @param fromIndex * @return */ public static int getPathIndex(String fileName, int fromIndex) { int point = fileName.indexOf("/", fromIndex); if (point == -1) { point = fileName.indexOf("", fromIndex); } return point; } /** * 將文件名中的類型部分去掉。 * * @param filename * @return */ public static String removeFileExt(String filename) { int index = filename.lastIndexOf("."); if (index != -1) { return filename.substring(0, index); } else { return filename; } } /** * 得到相對路徑。 文件名不是目錄名的子節點時返回文件名。 * * @param pathName * @param fileName * @return */ public static String getSubpath(String pathName, String fileName) { int index = fileName.indexOf(pathName); if (index != -1) { return fileName.substring(index + pathName.length() + 1); } else { return fileName; } } /** * 刪除一個文件。 * * @param filename * @throws IOException */ public static void deleteFile(String filename) throws IOException { File file = new File(filename); if (file.isDirectory()) { throw new IOException("IOException -> BadInputException: not a file."); } if (!file.exists()) { throw new IOException("IOException -> BadInputException: file is not exist."); } if (!file.delete()) { throw new IOException("Cannot delete file. filename = " + filename); } } /** * 刪除文件夾及其下面的子文件夾 * * @param dir * @throws IOException */ public static void deleteDir(File dir) throws IOException { if (dir.isFile()) throw new IOException("IOException -> BadInputException: not a directory."); File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isFile()) { file.delete(); } else { deleteDir(file); } } } dir.delete(); } /** * 復制文件 * * @param src * @param dst * @throws Exception */ public static void copy(File src, File dst) throws Exception { int BUFFER_SIZE = 4096; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { throw e; } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } in = null; } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } out = null; } } } /** * @復制文件,支持把源文件內容追加到目標文件末尾 * @param src * @param dst * @param append * @throws Exception */ public static void copy(File src, File dst, boolean append) throws Exception { int BUFFER_SIZE = 4096; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst, append), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { throw e; } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } in = null; } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } out = null; } } } }
Q2:第二個輸入輸出流封裝類
package com.io1; import java.io.*; import java.util.StringTokenizer; public class FileUtil2 { private static String message; /** * 讀取文本文件內容 * * @param filePathAndName * 帶有完整絕對路徑的文件名 * @param encoding * 文本文件打開的編碼方式 * @return 返回文本文件的內容 */ public static String readTxt(String filePathAndName, String encoding) throws IOException { encoding = encoding.trim(); StringBuffer str = new StringBuffer(""); String st = ""; try { FileInputStream fs = new FileInputStream(filePathAndName); InputStreamReader isr; if (encoding.equals("")) { isr = new InputStreamReader(fs); } else { isr = new InputStreamReader(fs, encoding); } BufferedReader br = new BufferedReader(isr); try { String data = ""; while ((data = br.readLine()) != null) { str.append(data + " "); } } catch (Exception e) { str.append(e.toString()); } st = str.toString(); } catch (IOException es) { st = ""; } return st; } /** * @description 寫文件 * @param args * @throws UnsupportedEncodingException * @throws IOException */ public static boolean writeTxtFile(String content, File fileName, String encoding) { FileOutputStream o = null; boolean result=false; try { o = new FileOutputStream(fileName,true); o.write(content.getBytes(encoding)); result=true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (o != null) { try { o.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * * @param content * @param fileName * @return */ public static boolean writeTxtFile(String content,String fileName) { return writeTxtFile(content,new File(fileName),"UTF-8"); } /** * 新建目錄 * * @param folderPath * 目錄 * @return 返回目錄創建后的路徑 */ public static String createFolder(String folderPath) { String txt = folderPath; try { java.io.File myFilePath = new java.io.File(txt); txt = folderPath; if (!myFilePath.exists()) { myFilePath.mkdir(); } } catch (Exception e) { message = "創建目錄操作出錯"; } return txt; } /** * 多級目錄創建 * * @param folderPath * 准備要在本級目錄下創建新目錄的目錄路徑 例如 c:myf * @param paths * 無限級目錄參數,各級目錄以單數線區分 例如 a|b|c * @return 返回創建文件后的路徑 例如 c:myfac */ public static String createFolders(String folderPath, String paths) { String txts = folderPath; try { String txt; txts = folderPath; StringTokenizer st = new StringTokenizer(paths, "|"); for (int i = 0; st.hasMoreTokens(); i++) { txt = st.nextToken().trim(); if (txts.lastIndexOf("/") != -1) { txts = createFolder(txts + txt); } else { txts = createFolder(txts + txt + "/"); } } } catch (Exception e) { message = "創建目錄操作出錯!"; } return txts; } /** * 新建文件 * * @param filePathAndName * 文本文件完整絕對路徑及文件名 * @param fileContent * 文本文件內容 * @return */ public static void createFile(String filePathAndName, String fileContent) { try { String filePath = filePathAndName; filePath = filePath.toString(); File myFilePath = new File(filePath); if (!myFilePath.exists()) { myFilePath.createNewFile(); } FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); String strContent = fileContent; myFile.println(strContent); myFile.close(); resultFile.close(); } catch (Exception e) { message = "創建文件操作出錯"; } } /** * 有編碼方式的文件創建 * * @param filePathAndName * 文本文件完整絕對路徑及文件名 * @param fileContent * 文本文件內容 * @param encoding * 編碼方式 例如 GBK 或者 UTF-8 * @return */ public static void createFile(String filePathAndName, String fileContent, String encoding) { try { String filePath = filePathAndName; filePath = filePath.toString(); File myFilePath = new File(filePath); if (!myFilePath.exists()) { myFilePath.createNewFile(); } PrintWriter myFile = new PrintWriter(myFilePath, encoding); String strContent = fileContent; myFile.println(strContent); myFile.close(); } catch (Exception e) { message = "創建文件操作出錯"; } } /** * 刪除文件 * * @param filePathAndName * 文本文件完整絕對路徑及文件名 * @return Boolean 成功刪除返回true遭遇異常返回false */ public static boolean delFile(String filePathAndName) { boolean bea = false; try { String filePath = filePathAndName; File myDelFile = new File(filePath); if (myDelFile.exists()) { myDelFile.delete(); bea = true; } else { bea = false; message = (filePathAndName + "刪除文件操作出錯"); } } catch (Exception e) { message = e.toString(); } return bea; } /** * 刪除文件夾 * * @param folderPath * 文件夾完整絕對路徑 * @return */ public static void delFolder(String folderPath) { try { delAllFile(folderPath); // 刪除完里面所有內容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); // 刪除空文件夾 } catch (Exception e) { message = ("刪除文件夾操作出錯"); } } /** * 刪除指定文件夾下所有文件 * * @param path * 文件夾完整絕對路徑 * @return * @return */ public static boolean delAllFile(String path) { boolean bea = false; File file = new File(path); if (!file.exists()) { return bea; } if (!file.isDirectory()) { return bea; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);// 先刪除文件夾里面的文件 delFolder(path + "/" + tempList[i]);// 再刪除空文件夾 bea = true; } } return bea; } /** * 復制單個文件 * * @param oldPathFile * 准備復制的文件源 * @param newPathFile * 拷貝到新絕對路徑帶文件名 * @return */ public static void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { // 文件存在時 InputStream inStream = new FileInputStream(oldPathFile); // 讀入原文件 FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; // 字節數 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("復制單個文件操作出錯"); } } /** * 復制整個文件夾的內容 * * @param oldPath * 准備拷貝的目錄 * @param newPath * 指定絕對路徑的新目錄 * @return */ public static void copyFolder(String oldPath, String newPath) { try { new File(newPath).mkdirs(); // 如果文件夾不存在 則建立新文件夾 File a = new File(oldPath); String[] file = a.list(); File temp = null; for (int i = 0; i < file.length; i++) { if (oldPath.endsWith(File.separator)) { temp = new File(oldPath + file[i]); } else { temp = new File(oldPath + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString()); byte[] b = new byte[1024 * 5]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {// 如果是子文件夾 copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]); } } } catch (Exception e) { message = "復制整個文件夾內容操作出錯"; } } /** * 移動文件 * * @param oldPath * @param newPath * @return */ public static void moveFile(String oldPath, String newPath) { copyFile(oldPath, newPath); delFile(oldPath); } /** * 移動目錄 * * @param oldPath * @param newPath * @return */ public static void moveFolder(String oldPath, String newPath) { copyFolder(oldPath, newPath); delFolder(oldPath); } /** * 得到錯誤信息 */ public static String getMessage() { return message; } }
提示:以上兩個封裝類都可以,有些不同,下面有一些使用方法,大家可以根據下面例子好好理解
package com.io1; import java.io.File; import java.util.Date; public class FileUtilText { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub String path = "e:" + File.separator + "file07.txt"; String path2 = "e:" + File.separator + "file08.txt"; File f=new File("e:"+File.separator+"file07.txt"); File f2=new File("e:"+File.separator+"file08.txt"); /*if (FileUtil2.writeTxtFile("當前時間:"+new Date().toString(), path)) { System.out.println(FileUtil.readFile(path)); System.out.println(FileUtil2.readTxt(path, "UTF-8")); }*/ /*FileUtil2.writeTxtFile("沙發阿三發射點發順豐", f, "utf-8"); System.out.println(FileUtil2.readTxt(path, "utf-8")); System.out.println(FileUtil.getPathPart(path)); FileUtil.copy(f, f2, true);*/ //FileUtil.deleteFile(path2); System.out.println(FileUtil.readFile(path)); FileUtil.writeTxtFile("fas的發生", f, "utf-8"); } }
大家可以根據例子然后自己把封裝類都給用一便,這樣就會熟悉