书单推荐:成为Java顶级程序员架构师 ,这20来本(高薪)必看点击获取
½áºÏÒÔÇ°µÄÏîÄ¿¿ª·¢ÖÐÓöµ½µÄ²»Í¬µÄÎļþ²Ù×÷£¬ÔÚÕâÀï»ù±¾ÉÏÌáÈ¡³öÁËËùÓöµ½¹ýµÄÎļþ²Ù×÷µÄ¹¤¾ßÀà¡£
1 ÎÒÏîÄ¿ÖÐÓõ½µÄÎļþ¹¤¾ßÀà
1 ¶ÁÈ¡rawÎļþ¡¢fileÎļþ£¬drawableÎļþ£¬assetÎļþ£¬±ÈÈç±¾µØµÄjsonÊý¾Ý£¬±¾µØÎı¾µÈ£»
È磺String result =FileUtil.getString(context,¡±raw://first.json¡±)
2 ¶ÁÈ¡±¾µØµÄpropertyÎļþ£¬²¢×ª»¯ÎªhashMapÀàÐ͵ÄÊý¾Ý £¨simpleProperty2HashMap£©£»
3 ½«rawÎļþ¿½±´µ½Ö¸¶¨Ä¿Â¼£¨copyRawFile£©£»
4 »ù±¾Îļþ¶Áд²Ù×÷£¨readFile£¬writeFile£©£»
5 ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ ·¾¶£¨extractFilePath£©£»
6 ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ÎļþÃû(°üº¬À©Õ¹Ãû)
È磺d:\path\file.ext ¨C> file.ext£¨extractFileName£©
7 ¼ì²éÖ¸¶¨ÎļþµÄ·¾¶ÊÇ·ñ´æÔÚ£¨pathExists£©
8 ¼ì²éÖƶ¨ÎļþÊÇ·ñ´æÔÚ£¨fileExists£©
9 ´´½¨Ä¿Â¼£¨makeDir£©
10 ÒƳý×Ö·û´®ÖеÄBOMǰ׺£¨removeBomHeaderIfExists£©
package com.nsu.edu.library.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.text.TextUtils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; 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.InputStreamReader; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.Set; /** * Create By Anthony on 2016/1/15 * Class Note:Îļþ¹¤¾ßÀà * °üº¬ÄÚÈÝ£º * 1 ¶ÁÈ¡rawÎļþ¡¢fileÎļþ£¬drawableÎļþ£¬assetÎļþ£¬±ÈÈç±¾µØµÄjsonÊý¾Ý£¬±¾µØÎı¾µÈ£» * È磺String result =FileUtil.getString(context,"raw://first.json") * 2 ¶ÁÈ¡±¾µØµÄpropertyÎļþ£¬²¢×ª»¯ÎªhashMapÀàÐ͵ÄÊý¾Ý£¨simpleProperty2HashMap£©£» * 3 ½«rawÎļþ¿½±´µ½Ö¸¶¨Ä¿Â¼£¨copyRawFile£©£» * 4 »ù±¾Îļþ¶Áд²Ù×÷£¨readFile£¬writeFile£©£» * 5 ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ ·¾¶£¨extractFilePath£©£» * 6 ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ÎļþÃû(°üº¬À©Õ¹Ãû) È磺d:\path\file.ext --> file.ext£¨extractFileName£© *7 ¼ì²éÖ¸¶¨ÎļþµÄ·¾¶ÊÇ·ñ´æÔÚ£¨pathExists£© *8 ¼ì²éÖƶ¨ÎļþÊÇ·ñ´æÔÚ£¨fileExists£© *9 ´´½¨Ä¿Â¼£¨makeDir£© *10 ÒƳý×Ö·û´®ÖеÄBOMǰ׺£¨removeBomHeaderIfExists£© */ public class FileUtil { public static final String ASSETS_PREFIX = "file://android_assets/"; public static final String ASSETS_PREFIX2 = "file://android_asset/"; public static final String ASSETS_PREFIX3 = "assets://"; public static final String ASSETS_PREFIX4 = "asset://"; public static final String RAW_PREFIX = "file://android_raw/"; public static final String RAW_PREFIX2 = "raw://"; public static final String FILE_PREFIX = "file://"; public static final String DRAWABLE_PREFIX = "drawable://"; public static InputStream getStream(Context context, String url) throws IOException { String lowerUrl = url.toLowerCase(); InputStream is; if (lowerUrl.startsWith(ASSETS_PREFIX)) { String assetPath = url.substring(ASSETS_PREFIX.length()); is = getAssetsStream(context, assetPath); } else if (lowerUrl.startsWith(ASSETS_PREFIX2)) { String assetPath = url.substring(ASSETS_PREFIX2.length()); is = getAssetsStream(context, assetPath); } else if (lowerUrl.startsWith(ASSETS_PREFIX3)) { String assetPath = url.substring(ASSETS_PREFIX3.length()); is = getAssetsStream(context, assetPath); } else if (lowerUrl.startsWith(ASSETS_PREFIX4)) { String assetPath = url.substring(ASSETS_PREFIX4.length()); is = getAssetsStream(context, assetPath); } else if (lowerUrl.startsWith(RAW_PREFIX)) { String rawName = url.substring(RAW_PREFIX.length()); is = getRawStream(context, rawName); } else if (lowerUrl.startsWith(RAW_PREFIX2)) { String rawName = url.substring(RAW_PREFIX2.length()); is = getRawStream(context, rawName); } else if (lowerUrl.startsWith(FILE_PREFIX)) { String filePath = url.substring(FILE_PREFIX.length()); is = getFileStream(filePath); } else if (lowerUrl.startsWith(DRAWABLE_PREFIX)) { String drawableName = url.substring(DRAWABLE_PREFIX.length()); is = getDrawableStream(context, drawableName); } else { throw new IllegalArgumentException(String.format("Unsupported url: %s \n" + "Supported: \n%sxxx\n%sxxx\n%sxxx", url, ASSETS_PREFIX, RAW_PREFIX, FILE_PREFIX)); } return is; } private static InputStream getAssetsStream(Context context, String path) throws IOException { return context.getAssets().open(path); } private static InputStream getFileStream(String path) throws IOException { return new FileInputStream(path); } private static InputStream getRawStream(Context context, String rawName) throws IOException { int id = context.getResources().getIdentifier(rawName, "raw", context.getPackageName()); if (id != 0) { try { return context.getResources().openRawResource(id); } catch (Exception e) { e.printStackTrace(); } } throw new IOException(String.format("raw of id: %s from %s not found", id, rawName)); } private static InputStream getDrawableStream(Context context, String rawName) throws IOException { int id = context.getResources().getIdentifier(rawName, "drawable", context.getPackageName()); if (id != 0) { BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(id); Bitmap bitmap = drawable.getBitmap(); ByteArrayOutputStream os = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, os); return new ByteArrayInputStream(os.toByteArray()); } throw new IOException(String.format("bitmap of id: %s from %s not found", id, rawName)); } public static String getString(Context context, String url) throws IOException { return getString(context, url, "UTF-8"); } public static String getString(Context context, String url, String encoding) throws IOException { String result = readStreamString(getStream(context, url), encoding); if (result.startsWith("\ufeff")) { result = result.substring(1); } return result; } public static String readStreamString(InputStream is, String encoding) throws IOException { return new String(readStream(is), encoding); } public static byte[] readStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int readlen; while ((readlen = is.read(buf)) >= 0) { baos.write(buf, 0, readlen); } baos.close(); return baos.toByteArray(); } public static Bitmap getDrawableBitmap(Context context, String rawName) { int id = context.getResources().getIdentifier(rawName, "drawable", context.getPackageName()); if (id != 0) { BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(id); if (drawable != null) { return drawable.getBitmap(); } } return null; } /** * ¶ÁÈ¡PropertyÎļþ */ public static HashMap<String, String> simpleProperty2HashMap(Context context, String path) { try { InputStream is = getStream(context, path); return simpleProperty2HashMap(is); } catch (IOException e) { e.printStackTrace(); } return new HashMap<String, String>(); } private static HashMap<String, String> simpleProperty2HashMap(InputStream in) throws IOException { HashMap<String, String> hashMap = new HashMap<String, String>(); Properties properties = new Properties(); properties.load(in); in.close(); Set keyValue = properties.keySet(); for (Iterator it = keyValue.iterator(); it.hasNext(); ) { String key = (String) it.next(); hashMap.put(key, (String) properties.get(key)); } return hashMap; } /** * ½«rawÎļþ¿½±´µ½Ö¸¶¨Ä¿Â¼ */ public static void copyRawFile(Context ctx, String rawFileName, String to) { String[] names = rawFileName.split("\\."); String toFile = to + "/" + names[0] + "." + names[1]; File file = new File(toFile); if (file.exists()) { return; } try { InputStream is = getStream(ctx, "raw://" + names[0]); OutputStream os = new FileOutputStream(toFile); int byteCount = 0; byte[] bytes = new byte[1024]; while ((byteCount = is.read(bytes)) != -1) { os.write(bytes, 0, byteCount); } os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } } /** * »ù±¾Îļþ²Ù×÷ */ public static String FILE_READING_ENCODING = "UTF-8"; public static String FILE_WRITING_ENCODING = "UTF-8"; public static String readFile(String _sFileName, String _sEncoding) throws Exception { StringBuffer buffContent = null; String sLine; FileInputStream fis = null; BufferedReader buffReader = null; if (_sEncoding == null || "".equals(_sEncoding)) { _sEncoding = FILE_READING_ENCODING; } try { fis = new FileInputStream(_sFileName); buffReader = new BufferedReader(new InputStreamReader(fis, _sEncoding)); boolean zFirstLine = "UTF-8".equalsIgnoreCase(_sEncoding); while ((sLine = buffReader.readLine()) != null) { if (buffContent == null) { buffContent = new StringBuffer(); } else { buffContent.append("\n"); } if (zFirstLine) { sLine = removeBomHeaderIfExists(sLine); zFirstLine = false; } buffContent.append(sLine); }// end while return (buffContent == null ? "" : buffContent.toString()); } catch (FileNotFoundException ex) { throw new Exception("Òª¶ÁÈ¡µÄÎļþûÓÐÕÒµ½!", ex); } catch (IOException ex) { throw new Exception("¶ÁÈ¡Îļþʱ´íÎó!", ex); } finally { // Ôö¼ÓÒ쳣ʱ×ÊÔ´µÄÊÍ·Å try { if (buffReader != null) buffReader.close(); if (fis != null) fis.close(); } catch (Exception ex) { ex.printStackTrace(); } } } public static File writeFile(InputStream is, String path, boolean isOverride) throws Exception { String sPath = extractFilePath(path); if (!pathExists(sPath)) { makeDir(sPath, true); } if (!isOverride && fileExists(path)) { if(path.contains(".")) { String suffix = path.substring(path.lastIndexOf(".")); String pre = path.substring(0, path.lastIndexOf(".")); path = pre + "_" + TimeUtils.getNowTime() + suffix; } else { path = path + "_" + TimeUtils.getNowTime(); } } FileOutputStream os = null; File file = null; try { file = new File(path); os = new FileOutputStream(file); int byteCount = 0; byte[] bytes = new byte[1024]; while ((byteCount = is.read(bytes)) != -1) { os.write(bytes, 0, byteCount); } os.flush(); return file; } catch (Exception e) { e.printStackTrace(); throw new Exception("дÎļþ´íÎó", e); } finally { try { if (os != null) os.close(); if (is != null) is.close(); } catch (Exception e) { e.printStackTrace(); } } } public static File writeFile(String path, String content, String encoding, boolean isOverride) throws Exception { if (TextUtils.isEmpty(encoding)) { encoding = FILE_WRITING_ENCODING; } InputStream is = new ByteArrayInputStream(content.getBytes(encoding)); return writeFile(is, path, isOverride); } /** * ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ ·¾¶£¨°üÀ¨£ºDrive+Directroy ) * * @param _sFilePathName * @return */ public static String extractFilePath(String _sFilePathName) { int nPos = _sFilePathName.lastIndexOf('/'); if (nPos < 0) { nPos = _sFilePathName.lastIndexOf('\\'); } return (nPos >= 0 ? _sFilePathName.substring(0, nPos + 1) : ""); } /** * ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ÎļþÃû(°üº¬À©Õ¹Ãû) <br> * È磺d:\path\file.ext --> file.ext * * @param _sFilePathName * @return */ public static String extractFileName(String _sFilePathName) { return extractFileName(_sFilePathName, File.separator); } /** * ´ÓÎļþµÄÍêÕû·¾¶Ãû£¨Â·¾¶+ÎļþÃû£©ÖÐÌáÈ¡ÎļþÃû(°üº¬À©Õ¹Ãû) <br> * È磺d:\path\file.ext --> file.ext * * @param _sFilePathName È«Îļþ·¾¶Ãû * @param _sFileSeparator Îļþ·Ö¸ô·û * @return */ public static String extractFileName(String _sFilePathName, String _sFileSeparator) { int nPos = -1; if (_sFileSeparator == null) { nPos = _sFilePathName.lastIndexOf(File.separatorChar); if (nPos < 0) { nPos = _sFilePathName .lastIndexOf(File.separatorChar == '/' ? '\\' : '/'); } } else { nPos = _sFilePathName.lastIndexOf(_sFileSeparator); } if (nPos < 0) { return _sFilePathName; } return _sFilePathName.substring(nPos + 1); } /** * ¼ì²éÖ¸¶¨ÎļþµÄ·¾¶ÊÇ·ñ´æÔÚ * * @param _sPathFileName ÎļþÃû³Æ(º¬Â·¾¶£© * @return Èô´æÔÚ£¬Ôò·µ»Øtrue£»·ñÔò£¬·µ»Øfalse */ public static boolean pathExists(String _sPathFileName) { String sPath = extractFilePath(_sPathFileName); return fileExists(sPath); } public static boolean fileExists(String _sPathFileName) { File file = new File(_sPathFileName); return file.exists(); } /** * ´´½¨Ä¿Â¼ * * @param _sDir Ŀ¼Ãû³Æ * @param _bCreateParentDir Èç¹û¸¸Ä¿Â¼²»´æÔÚ£¬ÊÇ·ñ´´½¨¸¸Ä¿Â¼ * @return */ public static boolean makeDir(String _sDir, boolean _bCreateParentDir) { boolean zResult = false; File file = new File(_sDir); if (_bCreateParentDir) zResult = file.mkdirs(); // Èç¹û¸¸Ä¿Â¼²»´æÔÚ£¬Ôò´´½¨ËùÓбØÐèµÄ¸¸Ä¿Â¼ else zResult = file.mkdir(); // Èç¹û¸¸Ä¿Â¼²»´æÔÚ£¬²»×ö´¦Àí if (!zResult) zResult = file.exists(); return zResult; } /** * ÒƳý×Ö·û´®ÖеÄBOMǰ׺ * * @param _sLine ÐèÒª´¦ÀíµÄ×Ö·û´® * @return ÒƳýBOMºóµÄ×Ö·û´®. */ private static String removeBomHeaderIfExists(String _sLine) { if (_sLine == null) { return null; } String line = _sLine; if (line.length() > 0) { char ch = line.charAt(0); // ʹÓÃwhileÊÇÒòΪÓÃһЩ¹¤¾ß¿´µ½¹ýijЩÎļþÇ°¼¸¸ö×Ö½Ú¶¼ÊÇ0xfffe. // 0xfeff,0xfffeÊÇ×Ö½ÚÐòµÄ²»Í¬´¦Àí.JVMÖÐ,Ò»°ãÊÇ0xfeff while ((ch == 0xfeff || ch == 0xfffe)) { line = line.substring(1); if (line.length() == 0) { break; } ch = line.charAt(0); } } return line; } }
2 ÍøÉϵŤ¾ßÀà
Õâ¸ö¹¤¾ßÀàÒ²´óͬСÒì¡£ÆäÖÐÒ²ÓкܶàºÍÎÒÉÏÃæÖظ´µÄһЩ·½·¨£¬Ò²ÓÐÉÏÃæûÓеķ½·¨¡£×ª×ÔTrineaµÄandroid-commonÏîÄ¿¡£ÕâÀïÖ±½ÓÌù³öÀ´£¬²»×öÈκθü¸Ä¡£Ï£ÍûÄܶԿ´µ½µÄÈËÓаïÖú¡£Ò²×öÒ»¸ö±Ê¼Ç¡£
package com.nsu.edu.library.utils; import android.text.TextUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * File Utils * <ul> * Read or write file * <li>{@link #readFile(String, String)} read file</li> * <li>{@link #readFileToList(String, String)} read file to string list</li> * <li>{@link #writeFile(String, String, boolean)} write file from String</li> * <li>{@link #writeFile(String, String)} write file from String</li> * <li>{@link #writeFile(String, List, boolean)} write file from String List</li> * <li>{@link #writeFile(String, List)} write file from String List</li> * <li>{@link #writeFile(String, InputStream)} write file</li> * <li>{@link #writeFile(String, InputStream, boolean)} write file</li> * <li>{@link #writeFile(File, InputStream)} write file</li> * <li>{@link #writeFile(File, InputStream, boolean)} write file</li> * </ul> * <ul> * Operate file * <li>{@link #moveFile(File, File)} or {@link #moveFile(String, String)}</li> * <li>{@link #copyFile(String, String)}</li> * <li>{@link #getFileExtension(String)}</li> * <li>{@link #getFileName(String)}</li> * <li>{@link #getFileNameWithoutExtension(String)}</li> * <li>{@link #getFileSize(String)}</li> * <li>{@link #deleteFile(String)}</li> * <li>{@link #isFileExist(String)}</li> * <li>{@link #isFolderExist(String)}</li> * <li>{@link #makeFolders(String)}</li> * <li>{@link #makeDirs(String)}</li> * </ul> * * @author <a href="http://www.trinea.cn" rel="external nofollow" target="_blank">Trinea</a> 2012-5-12 */ public class FileUtils { public final static String FILE_EXTENSION_SEPARATOR = "."; private FileUtils() { throw new AssertionError(); } /** * read file * * @param filePath * @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>} * @return if file not exist, return null, else return content of file * @throws RuntimeException if an error occurs while operator BufferedReader */ public static StringBuilder readFile(String filePath, String charsetName) { File file = new File(filePath); StringBuilder fileContent = new StringBuilder(""); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { if (!fileContent.toString().equals("")) { fileContent.append("\r\n"); } fileContent.append(line); } return fileContent; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(reader); } } /** * write file * * @param filePath * @param content * @param append is append, if true, write to the end of file, else clear content of file and write into it * @return return false if content is empty, true otherwise * @throws RuntimeException if an error occurs while operator FileWriter */ public static boolean writeFile(String filePath, String content, boolean append) { if (StringUtils.isEmpty(content)) { return false; } FileWriter fileWriter = null; try { makeDirs(filePath); fileWriter = new FileWriter(filePath, append); fileWriter.write(content); return true; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(fileWriter); } } /** * write file * * @param filePath * @param contentList * @param append is append, if true, write to the end of file, else clear content of file and write into it * @return return false if contentList is empty, true otherwise * @throws RuntimeException if an error occurs while operator FileWriter */ public static boolean writeFile(String filePath, List<String> contentList, boolean append) { if (ListUtils.isEmpty(contentList)) { return false; } FileWriter fileWriter = null; try { makeDirs(filePath); fileWriter = new FileWriter(filePath, append); int i = 0; for (String line : contentList) { if (i++ > 0) { fileWriter.write("\r\n"); } fileWriter.write(line); } return true; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(fileWriter); } } /** * write file, the string will be written to the begin of the file * * @param filePath * @param content * @return */ public static boolean writeFile(String filePath, String content) { return writeFile(filePath, content, false); } /** * write file, the string list will be written to the begin of the file * * @param filePath * @param contentList * @return */ public static boolean writeFile(String filePath, List<String> contentList) { return writeFile(filePath, contentList, false); } /** * write file, the bytes will be written to the begin of the file * * @param filePath * @param stream * @return * @see {@link #writeFile(String, InputStream, boolean)} */ public static boolean writeFile(String filePath, InputStream stream) { return writeFile(filePath, stream, false); } /** * write file * * @param file the file to be opened for writing. * @param stream the input stream * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning * @return return true * @throws RuntimeException if an error occurs while operator FileOutputStream */ public static boolean writeFile(String filePath, InputStream stream, boolean append) { return writeFile(filePath != null ? new File(filePath) : null, stream, append); } /** * write file, the bytes will be written to the begin of the file * * @param file * @param stream * @return * @see {@link #writeFile(File, InputStream, boolean)} */ public static boolean writeFile(File file, InputStream stream) { return writeFile(file, stream, false); } /** * write file * * @param file the file to be opened for writing. * @param stream the input stream * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning * @return return true * @throws RuntimeException if an error occurs while operator FileOutputStream */ public static boolean writeFile(File file, InputStream stream, boolean append) { OutputStream o = null; try { makeDirs(file.getAbsolutePath()); o = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException occurred. ", e); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(o); IOUtils.close(stream); } } /** * move file * * @param sourceFilePath * @param destFilePath */ public static void moveFile(String sourceFilePath, String destFilePath) { if (TextUtils.isEmpty(sourceFilePath) || TextUtils.isEmpty(destFilePath)) { throw new RuntimeException("Both sourceFilePath and destFilePath cannot be null."); } moveFile(new File(sourceFilePath), new File(destFilePath)); } /** * move file * * @param srcFile * @param destFile */ public static void moveFile(File srcFile, File destFile) { boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); deleteFile(srcFile.getAbsolutePath()); } } /** * copy file * * @param sourceFilePath * @param destFilePath * @return * @throws RuntimeException if an error occurs while operator FileOutputStream */ public static boolean copyFile(String sourceFilePath, String destFilePath) { InputStream inputStream = null; try { inputStream = new FileInputStream(sourceFilePath); } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException occurred. ", e); } return writeFile(destFilePath, inputStream); } /** * read file to string list, a element of list is a line * * @param filePath * @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>} * @return if file not exist, return null, else return content of file * @throws RuntimeException if an error occurs while operator BufferedReader */ public static List<String> readFileToList(String filePath, String charsetName) { File file = new File(filePath); List<String> fileContent = new ArrayList<String>(); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { fileContent.add(line); } return fileContent; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(reader); } } /** * get file name from path, not include suffix * * <pre> * getFileNameWithoutExtension(null) = null * getFileNameWithoutExtension("") = "" * getFileNameWithoutExtension(" ") = " " * getFileNameWithoutExtension("abc") = "abc" * getFileNameWithoutExtension("a.mp3") = "a" * getFileNameWithoutExtension("a.b.rmvb") = "a.b" * getFileNameWithoutExtension("c:\\") = "" * getFileNameWithoutExtension("c:\\a") = "a" * getFileNameWithoutExtension("c:\\a.b") = "a" * getFileNameWithoutExtension("c:a.txt\\a") = "a" * getFileNameWithoutExtension("/home/admin") = "admin" * getFileNameWithoutExtension("/home/admin/a.txt/b.mp3") = "b" * </pre> * * @param filePath * @return file name from path, not include suffix * @see */ public static String getFileNameWithoutExtension(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR); int filePosi = filePath.lastIndexOf(File.separator); if (filePosi == -1) { return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi)); } if (extenPosi == -1) { return filePath.substring(filePosi + 1); } return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1)); } /** * get file name from path, include suffix * * <pre> * getFileName(null) = null * getFileName("") = "" * getFileName(" ") = " " * getFileName("a.mp3") = "a.mp3" * getFileName("a.b.rmvb") = "a.b.rmvb" * getFileName("abc") = "abc" * getFileName("c:\\") = "" * getFileName("c:\\a") = "a" * getFileName("c:\\a.b") = "a.b" * getFileName("c:a.txt\\a") = "a" * getFileName("/home/admin") = "admin" * getFileName("/home/admin/a.txt/b.mp3") = "b.mp3" * </pre> * * @param filePath * @return file name from path, include suffix */ public static String getFileName(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int filePosi = filePath.lastIndexOf(File.separator); return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1); } /** * get folder name from path * * <pre> * getFolderName(null) = null * getFolderName("") = "" * getFolderName(" ") = "" * getFolderName("a.mp3") = "" * getFolderName("a.b.rmvb") = "" * getFolderName("abc") = "" * getFolderName("c:\\") = "c:" * getFolderName("c:\\a") = "c:" * getFolderName("c:\\a.b") = "c:" * getFolderName("c:a.txt\\a") = "c:a.txt" * getFolderName("c:a\\b\\c\\d.txt") = "c:a\\b\\c" * getFolderName("/home/admin") = "/home" * getFolderName("/home/admin/a.txt/b.mp3") = "/home/admin/a.txt" * </pre> * * @param filePath * @return */ public static String getFolderName(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int filePosi = filePath.lastIndexOf(File.separator); return (filePosi == -1) ? "" : filePath.substring(0, filePosi); } /** * get suffix of file from path * * <pre> * getFileExtension(null) = "" * getFileExtension("") = "" * getFileExtension(" ") = " " * getFileExtension("a.mp3") = "mp3" * getFileExtension("a.b.rmvb") = "rmvb" * getFileExtension("abc") = "" * getFileExtension("c:\\") = "" * getFileExtension("c:\\a") = "" * getFileExtension("c:\\a.b") = "b" * getFileExtension("c:a.txt\\a") = "" * getFileExtension("/home/admin") = "" * getFileExtension("/home/admin/a.txt/b") = "" * getFileExtension("/home/admin/a.txt/b.mp3") = "mp3" * </pre> * * @param filePath * @return */ public static String getFileExtension(String filePath) { if (StringUtils.isBlank(filePath)) { return filePath; } int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR); int filePosi = filePath.lastIndexOf(File.separator); if (extenPosi == -1) { return ""; } return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1); } /** * Creates the directory named by the trailing filename of this file, including the complete directory path required * to create this directory. <br/> * <br/> * <ul> * <strong>Attentions:</strong> * <li>makeDirs("C:\\Users\\Trinea") can only create users folder</li> * <li>makeFolder("C:\\Users\\Trinea\\") can create Trinea folder</li> * </ul> * * @param filePath * @return true if the necessary directories have been created or the target directory already exists, false one of * the directories can not be created. * <ul> * <li>if {@link FileUtils#getFolderName(String)} return null, return false</li> * <li>if target directory already exists, return true</li> * <li>return {@link File#makeFolder}</li> * </ul> */ public static boolean makeDirs(String filePath) { String folderName = getFolderName(filePath); if (StringUtils.isEmpty(folderName)) { return false; } File folder = new File(folderName); return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs(); } /** * @param filePath * @return * @see #makeDirs(String) */ public static boolean makeFolders(String filePath) { return makeDirs(filePath); } /** * Indicates if this file represents a file on the underlying file system. * * @param filePath * @return */ public static boolean isFileExist(String filePath) { if (StringUtils.isBlank(filePath)) { return false; } File file = new File(filePath); return (file.exists() && file.isFile()); } /** * Indicates if this file represents a directory on the underlying file system. * * @param directoryPath * @return */ public static boolean isFolderExist(String directoryPath) { if (StringUtils.isBlank(directoryPath)) { return false; } File dire = new File(directoryPath); return (dire.exists() && dire.isDirectory()); } /** * delete file or directory * <ul> * <li>if path is null or empty, return true</li> * <li>if path not exist, return true</li> * <li>if path exist, delete recursion. return true</li> * <ul> * * @param path * @return */ public static boolean deleteFile(String path) { if (StringUtils.isBlank(path)) { return true; } File file = new File(path); if (!file.exists()) { return true; } if (file.isFile()) { return file.delete(); } if (!file.isDirectory()) { return false; } for (File f : file.listFiles()) { if (f.isFile()) { f.delete(); } else if (f.isDirectory()) { deleteFile(f.getAbsolutePath()); } } return file.delete(); } /** * get file size * <ul> * <li>if path is null or empty, return -1</li> * <li>if path exist and it is a file, return file size, else return -1</li> * <ul> * * @param path * @return returns the length of this file in bytes. returns -1 if the file does not exist. */ public static long getFileSize(String path) { if (StringUtils.isBlank(path)) { return -1; } File file = new File(path); return (file.exists() && file.isFile() ? file.length() : -1); } }
ÒÔÉϾÍÊDZ¾ÎĵÄÈ«²¿ÄÚÈÝ£¬Ï£Íû¶Ô´ó¼ÒµÄѧϰÓÐËù°ïÖú£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö½Å±¾Ö®¼Ò¡£
转载请注明:谷谷点程序 » 值得分享的超全文件工具类FileUtil