文件工具类,可用于读写文件及对文件进行操作。如:
readFile(String filePath) 读文件
writeFile(String filePath, String content, boolean append) 写文件
getFileSize(String path) 得到文件大小
deleteFile(String path) 删除文件
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;
import android.text.TextUtils;
/**
* File Utils
*
* Read or write file
* - {@link #readFile(String, String)} read file
* - {@link #readFileToList(String, String)} read file to string list
* - {@link #writeFile(String, String, boolean)} write file from String
* - {@link #writeFile(String, String)} write file from String
* - {@link #writeFile(String, List, boolean)} write file from String List
* - {@link #writeFile(String, List)} write file from String List
* - {@link #writeFile(String, InputStream)} write file
* - {@link #writeFile(String, InputStream, boolean)} write file
* - {@link #writeFile(File, InputStream)} write file
* - {@link #writeFile(File, InputStream, boolean)} write file
*
*
* Operate file
* - {@link #moveFile(File, File)} or {@link #moveFile(String, String)}
* - {@link #copyFile(String, String)}
* - {@link #getFileExtension(String)}
* - {@link #getFileName(String)}
* - {@link #getFileNameWithoutExtension(String)}
* - {@link #getFileSize(String)}
* - {@link #deleteFile(String)}
* - {@link #isFileExist(String)}
* - {@link #isFolderExist(String)}
* - {@link #makeFolders(String)}
* - {@link #makeDirs(String)}
*
*/
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
charset}
* @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 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 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 true
, 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 true
, 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
charset}
* @return if file not exist, return null, else return content of file
* @throws RuntimeException 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);
}
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(reader);
}
}
/**
* 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
* - return {@link java.io.File#makeFolder}
*
*/
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
*
* - 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 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);
}
}
图片工具类,可用于Bitmap, byte array, Drawable之间进行转换以及图片缩放,目前功能薄弱,后面会进行增强。如:
bitmapToDrawable(Bitmap b) bimap转换为drawable
drawableToBitmap(Drawable d) drawable转换为bitmap
drawableToByte(Drawable d) drawable转换为byte
scaleImage(Bitmap org, float scaleWidth, float scaleHeight) 缩放图片
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
/**
* ImageUtils
*
* convert between Bitmap, byte array, Drawable
* - {@link #bitmapToByte(Bitmap)}
* - {@link #bitmapToDrawable(Bitmap)}
* - {@link #byteToBitmap(byte[])}
* - {@link #byteToDrawable(byte[])}
* - {@link #drawableToBitmap(Drawable)}
* - {@link #drawableToByte(Drawable)}
*
*
* get image
* - {@link #getInputStreamFromUrl(String, int)}
* - {@link #getBitmapFromUrl(String, int)}
* - {@link #getDrawableFromUrl(String, int)}
*
*
* scale image
* - {@link #scaleImageTo(Bitmap, int, int)}
* - {@link #scaleImage(Bitmap, float, float)}
*
*/
public class ImageUtils {
private ImageUtils() {
throw new AssertionError();
}
/**
* convert Bitmap to byte array
*
* @param b
* @return
*/
public static byte[] bitmapToByte(Bitmap b) {
if (b == null) {
return null;
}
ByteArrayOutputStream o = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, o);
return o.toByteArray();
}
/**
* convert byte array to Bitmap
*
* @param b
* @return
*/
public static Bitmap byteToBitmap(byte[] b) {
return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);
}
/**
* convert Drawable to Bitmap
*
* @param d
* @return
*/
public static Bitmap drawableToBitmap(Drawable d) {
return d == null ? null : ((BitmapDrawable)d).getBitmap();
}
/**
* convert Bitmap to Drawable
*
* @param b
* @return
*/
public static Drawable bitmapToDrawable(Bitmap b) {
return b == null ? null : new BitmapDrawable(b);
}
/**
* convert Drawable to byte array
*
* @param d
* @return
*/
public static byte[] drawableToByte(Drawable d) {
return bitmapToByte(drawableToBitmap(d));
}
/**
* convert byte array to Drawable
*
* @param b
* @return
*/
public static Drawable byteToDrawable(byte[] b) {
return bitmapToDrawable(byteToBitmap(b));
}
/**
* get input stream from network by imageurl, you need to close inputStream yourself
*
* @param imageUrl
* @param readTimeOutMillis
* @return
* @see ImageUtils#getInputStreamFromUrl(String, int, boolean)
*/
public static InputStream getInputStreamFromUrl(String imageUrl, int readTimeOutMillis) {
return getInputStreamFromUrl(imageUrl, readTimeOutMillis, null);
}
/**
* get input stream from network by imageurl, you need to close inputStream yourself
*
* @param imageUrl
* @param readTimeOutMillis read time out, if less than 0, not set, in mills
* @param requestProperties http request properties
* @return
* @throws MalformedURLException
* @throws IOException
*/
public static InputStream getInputStreamFromUrl(String imageUrl, int readTimeOutMillis,
Map requestProperties) {
InputStream stream = null;
try {
URL url = new URL(imageUrl);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
HttpUtils.setURLConnection(requestProperties, con);
if (readTimeOutMillis > 0) {
con.setReadTimeout(readTimeOutMillis);
}
stream = con.getInputStream();
} catch (MalformedURLException e) {
IOUtils.close(stream);
throw new RuntimeException("MalformedURLException occurred. ", e);
} catch (IOException e) {
IOUtils.close(stream);
throw new RuntimeException("IOException occurred. ", e);
}
return stream;
}
/**
* get drawable by imageUrl
*
* @param imageUrl
* @param readTimeOutMillis
* @return
* @see ImageUtils#getDrawableFromUrl(String, int, boolean)
*/
public static Drawable getDrawableFromUrl(String imageUrl, int readTimeOutMillis) {
return getDrawableFromUrl(imageUrl, readTimeOutMillis, null);
}
/**
* get drawable by imageUrl
*
* @param imageUrl
* @param readTimeOutMillis read time out, if less than 0, not set, in mills
* @param requestProperties http request properties
* @return
*/
public static Drawable getDrawableFromUrl(String imageUrl, int readTimeOutMillis,
Map requestProperties) {
InputStream stream = getInputStreamFromUrl(imageUrl, readTimeOutMillis, requestProperties);
Drawable d = Drawable.createFromStream(stream, "src");
IOUtils.close(stream);
return d;
}
/**
* get Bitmap by imageUrl
*
* @param imageUrl
* @param readTimeOut
* @return
* @see ImageUtils#getBitmapFromUrl(String, int, boolean)
*/
public static Bitmap getBitmapFromUrl(String imageUrl, int readTimeOut) {
return getBitmapFromUrl(imageUrl, readTimeOut, null);
}
/**
* get Bitmap by imageUrl
*
* @param imageUrl
* @param requestProperties http request properties
* @return
*/
public static Bitmap getBitmapFromUrl(String imageUrl, int readTimeOut, Map requestProperties) {
InputStream stream = getInputStreamFromUrl(imageUrl, readTimeOut, requestProperties);
Bitmap b = BitmapFactory.decodeStream(stream);
IOUtils.close(stream);
return b;
}
/**
* scale image
*
* @param org
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap scaleImageTo(Bitmap org, int newWidth, int newHeight) {
return scaleImage(org, (float) newWidth / org.getWidth(), (float) newHeight / org.getHeight());
}
/**
* scale image
*
* @param org
* @param scaleWidth sacle of width
* @param scaleHeight scale of height
* @return
*/
public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) {
if (org == null) {
return null;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
}
}