package com.wpc.library.util.common; import android.graphics.Bitmap; 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.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; /** * File Utils *
}
* @return if file not exist, return null, else return content of file
* @throws IOException 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);
}
reader.close();
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* 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 true
* @throws IOException if an error occurs while operator FileWriter
*/
public static boolean writeFile(String filePath, String content, boolean append) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(filePath, append);
fileWriter.write(content);
fileWriter.close();
return true;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* write file
*
* @param filePath
* @param stream
* @return return true
* @throws IOException if an error occurs while operator FileWriter
*/
public static boolean writeFile(String filePath, InputStream stream) {
OutputStream o = null;
try {
o = new FileOutputStream(filePath);
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 {
if (o != null) {
try {
o.close();
stream.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* 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
*
charset}
* @return if file not exist, return null, else return content of file
* @throws IOException if an error occurs while operator BufferedReader
*/
public static List readFileToList(String filePath,
String charsetName) {
File file = new File(filePath);
List fileContent = new ArrayList();
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);
}
reader.close();
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* get file name from path, not include suffix
*
*
* 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"
*
*
* @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
*
*
* 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"
*
*
* @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
*
*
* 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"
*
*
* @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
*
*
* 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"
*
*
* @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.
*
*
* Attentions:
* - makeDirs("C:\\Users\\Trinea") can only create users folder
* - makeFolder("C:\\Users\\Trinea\\") can create Trinea folder
*
*
* @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.
*
* - if {@link FileUtils#getFolderName(String)} return null,
* return false
* - if target directory already exists, return true
*
*/
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()) || 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
*
* - if path is null or empty, return true
* - if path not exist, return true
* - if path exist, delete recursion. return true
*
*
* @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
*
* - if path is null or empty, return -1
* - if path exist and it is a file, return file size, else return -1
*
*
* @param path
* @return
*/
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);
}
/**
* 文件复制
*
* @param src
* @param dest
*/
public static void copyFile(File src, File dest) {
if (!src.exists() || src.length() <= 0)
return;
if (!dest.exists())
try {
File parent = dest.getParentFile();
if (!parent.exists())
parent.mkdirs();
dest.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
if (dest.exists()) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[8 * 1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("关闭输入流错误!");
}
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
System.out.println("关闭输出流错误!");
}
}
}
}
public static void saveBitmap(Bitmap bitmap, String path, String name) throws Exception {
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File file = new File(path + "/" + name);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
throw new Exception("文件创建失败");
}
try {
//文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(file);
//压缩图片,如果要保存png,就用Bitmap.CompressFormat.PNG,要保存jpg就用Bitmap.CompressFormat.JPEG,质量是100%,表示不压缩
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
//写入,这里会卡顿,因为图片较大
fileOutputStream.flush();
//记得要关闭写入流
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new Exception("文件不存在");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("文件保存失败");
}
}
public static String MD5(String filePath) {
BigInteger bi = null;
try {
byte[] buffer = new byte[8192];
int len = 0;
MessageDigest md = MessageDigest.getInstance("MD5");
File f = new File(filePath);
FileInputStream fis = new FileInputStream(f);
while ((len = fis.read(buffer)) != -1) {
md.update(buffer, 0, len);
}
fis.close();
byte[] b = md.digest();
bi = new BigInteger(1, b);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bi.toString(16);
}
}