关于IO流的工具类,可以节省很多的开发时间,具体内容大家可以看一看,有复制,获取文件内容,保存到文件中,保存Bitmap到文件中,对文件压缩和解压缩,直接从文件中获取JSON等等。
首先,定义常量
private static final String LOG_TAG = "IOUtilities";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static final String UTF8 = "utf-8";
public static boolean ensureDir(File file) {
boolean result = false;
if (file != null) {
if (file.exists()) {
result = true;
} else {
result = file.getParentFile().mkdirs();
}
}
return result;
}
1、复制
/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
* @throws java.io.IOException If any error occurs during the copy.
*/
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
public static void copyFile(File src, File dest) throws IOException {
if (src.exists()) {
FileChannel channel1 = new FileInputStream(src).getChannel();
FileChannel channel2 = new FileOutputStream(dest).getChannel();
channel1.transferTo(0, channel1.size(), channel2);
}
}
public static void copyDirectory(File src, File dest) throws IOException {
if (src.exists()) {
dest.mkdirs();
File[] files = src.listFiles();
if (files == null) {
return;
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
copyDirectory(file, new File(dest, file.getName()));
} else {
copyFile(file, new File(dest, file.getName()));
}
}
}
}
public static boolean ensureMkdir(final File dir) {
if (dir == null) {
return false;
}
File tempDir = dir;
int i = 1;
while (tempDir.exists()) {
tempDir = new File(dir.getParent(), dir.getName() + "(" + i + ")");
i++;
}
return tempDir.mkdir();
}
2、关闭流等
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
public static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Could not close stream", e);
}
}
}
/**
* Close an {@link SQLiteDatabase}.
* <p/>
* <br/>DO NOT close an database that you plan to reuse.
*
* @param db the database to close.
*/
public static void closeSQLiteDatabase(SQLiteDatabase db) {
if (db != null) {
try {
db.close();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not close db", e);
}
}
}
/**
* Close the cursor if necessary.
* <p/>
* <br/>DO NOT close an cursor that you plan to reuse.
*
* @param cursor the cursor to close.
*/
public static void closeCursor(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) {
try {
cursor.close();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not close cursor", e);
}
}
}
3、从文件中获取内容
public static String loadContent(File file) throws IOException {
Log.d(LOG_TAG, "file-->" + file.getPath());
if (file == null || !file.exists()) {
return null;
}
FileInputStream fileInputStream = new FileInputStream(file);
return loadContent(fileInputStream, UTF8);
}
public static String loadContent(InputStream stream, String encoding) throws IOException {
Reader reader = new InputStreamReader(stream, encoding);
CharArrayBuffer buffer = new CharArrayBuffer(stream.available());
try {
char[] tmp = new char[IO_BUFFER_SIZE];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
closeStream(reader);
}
int start = 0;
if (UTF8.equalsIgnoreCase(encoding) && buffer.length() > 0) {
if (buffer.charAt(0) == '\uFEFF') {
//skip utf-8 file BOM
start = 1;
}
}
return buffer.substring(start, buffer.length());
}
public static String readFileText(String file) {
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
return loadContent(stream, UTF8);
} catch (Exception e) {
Log.w(e);
} catch (OutOfMemoryError ee) {
Log.w(ee);
} finally {
closeStream(stream);
}
return null;
}
4、将内容保存到文件当中
/**
* 保存content到file中,默认采用utf-8编码方式
*
* @param file
* @param content
* @throws IOException
*/
public static void saveToFile(File file, String content) throws IOException {
saveToFile(file, content, UTF8);
}
/**
* 保存content到file中,可以指定编码方式
*
* @param file
* @param content
* @param encoding
* @throws IOException
*/
public static void saveToFile(File file, String content, String encoding) throws IOException {
OutputStreamWriter writer = null;
try {
ensureDir(file);
writer = new OutputStreamWriter(
new FileOutputStream(file), encoding);
writer.write(content);
} finally {
closeStream(writer);
}
}
/**
* 保存文件
*
* @param inputStream
* @param destFile
* @throws IOException
*/
public static void saveToFile(InputStream inputStream, File destFile) throws IOException {
if (inputStream == null || destFile == null) {
throw new IOException("inputStream or destFile is null.");
}
FileOutputStream fos = null;
try {
ensureDir(destFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} finally {
closeStream(fos);
}
}
/**
* 保存bitmap到文件中
*
* @param file
* @param bitmap
* @throws IOException
*/
public static void saveToFile(File file, Bitmap bitmap) throws IOException {
FileOutputStream out = null;
try {
ensureDir(file);
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
} finally {
closeStream(out);
}
}
public static void copyFile(File src, File dest) throws IOException {
if (src.exists()) {
FileChannel channel1 = new FileInputStream(src).getChannel();
FileChannel channel2 = new FileOutputStream(dest).getChannel();
channel1.transferTo(0, channel1.size(), channel2);
}
}
5、删除文件、文件夹
/**
* Deletes a file.
* <p/>
* <p>If Java impl fails, we will call linux command to do so.</p>
*
* @param file the file to delete.
* @param waitUntilDone whether wait until the linux command returns.
*/
public static void deleteFile(File file, boolean waitUntilDone) {
boolean success = file.delete();
if (!success) {
try {
String[] args = new String[]{
"rm",
"-rf",
file.toString()
};
Process proc = Runtime.getRuntime().exec(args);
if (waitUntilDone) {
int exitCode = proc.waitFor();
Log.d(LOG_TAG, "Linux rm -rf %s: %d.", file, exitCode);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Deletes a file.
* <p/>
* <p>If Java impl fails, we will call linux command to do so.</p>
*
* @param file the file to delete.
*/
public static void deleteFile(File file) {
deleteFile(file, true);
}
/**
* Deletes a file.
* <p/>
* <p>If Java impl fails, we will call linux command to do so.</p>
*
* @param path the path to the file to delete.
* @param waitUntilDone whether wait until the linux command returns.
*/
public static void deleteFile(String path, boolean waitUntilDone) {
deleteDir(new File(path), waitUntilDone);
}
/**
* Deletes a file.
* <p/>
* <p>If Java impl fails, we will call linux command to do so.</p>
*
* @param path the path to the file to delete.
*/
public static void deleteFile(String path) {
deleteDir(new File(path));
}
/**
* delete a file, if error happened, ignore this.
*
* @param path
*/
public static void deleteFileSafe(String path) {
try {
deleteDir(new File(path));
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Clean a specified directory.
*
* @param dir the directory to clean.
*/
public static void cleanDir(final File dir) {
deleteDir(dir, false);
}
/**
* Clean a specified directory.
*
* @param dir the directory to clean.
* @param filter the filter to determine which file or directory to delete.
*/
public static void cleanDir(final File dir, final FilenameFilter filter) {
deleteDir(dir, false, filter);
}
/**
* Clean a specified directory.
*
* @param dir the directory to clean.
* @param filter the filter to determine which file or directory to delete.
*/
public static void cleanDir(final File dir, final FileFilter filter) {
deleteDir(dir, false, filter);
}
public static void deleteDir(final String dir) {
deleteDir(new File(dir));
}
/**
* Delete a specified directory.
*
* @param dir the directory to clean.
*/
public static void deleteDir(final File dir) {
deleteDir(dir, true);
}
/**
* Delete a specified directory.
*
* @param dir the directory to clean.
* @param filter the filter to determine which file or directory to delete.
*/
public static void deleteDir(final File dir, final FileFilter filter) {
deleteDir(dir, true, filter);
}
/**
* Delete a specified directory.
*
* @param dir the directory to clean.
* @param filter the filter to determine which file or directory to delete.
*/
public static void deleteDir(final File dir, final FilenameFilter filter) {
deleteDir(dir, true, filter);
}
/**
* Delete a specified directory.
*
* @param dir the directory to clean.
* @param removeDir true to remove the {@code dir}.
*/
public static void deleteDir(final File dir, final boolean removeDir) {
if (dir != null && dir.isDirectory()) {
final File[] files = dir.listFiles();
if (files != null && files.length > 0) {
for (final File file : files) {
if (file.isDirectory()) {
deleteDir(file, removeDir);
} else {
file.delete();
}
}
}
if (removeDir) {
dir.delete();
}
}
}
/**
* Delete a specified directory.
*
* @param dir the directory to clean.
* @param removeDir true to remove the {@code dir}.
* @param filter the filter to determine which file or directory to delete.
*/
public static void deleteDir(final File dir, final boolean removeDir, final FileFilter filter) {
if (dir != null && dir.isDirectory()) {
final File[] files = dir.listFiles(filter);
if (files != null) {
for (final File file : files) {
if (file.isDirectory()) {
deleteDir(file, removeDir, filter);
} else {
file.delete();
}
}
}
if (removeDir) {
dir.delete();
}
}
}
/**
* Delete a specified directory.
*
* @param dir the directory to clean.
* @param removeDir true to remove the {@code dir}.
* @param filter the filter to determine which file or directory to delete.
*/
public static void deleteDir(final File dir, final boolean removeDir, final FilenameFilter filter) {
if (dir != null && dir.isDirectory()) {
final File[] files = dir.listFiles(filter);
if (files != null) {
for (final File file : files) {
if (file.isDirectory()) {
deleteDir(file, removeDir, filter);
} else {
file.delete();
}
}
}
if (removeDir) {
dir.delete();
}
}
}
* Clear content of a file.
* If the file doesn't exist, it will return false.
*
* @param file the file to clear.
* @return true if file becomes empty, false otherwise.
*/
public static boolean clearFile(File file) {
if (file == null || !file.exists()) {
return false;
}
if (file.length() == 0) {
return true;
}
boolean result = true;
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
out.write("".getBytes(UTF8));
} catch (FileNotFoundException e) {
result = false;
Log.e(e.toString());
} catch (IOException e) {
result = false;
Log.e(e.toString());
} finally {
closeStream(out);
}
return result;
}
6、获取byte[]
public static byte[] loadBytes(InputStream stream) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try {
byte[] tmp = new byte[IO_BUFFER_SIZE];
int l;
while ((l = stream.read(tmp)) != -1) {
bytes.write(tmp, 0, l);
}
} finally {
closeStream(stream);
}
return bytes.toByteArray();
}
/**
* 添加接口直接从文件读取byte[]内容
*
* @param file 待读取的文件
* @return 读取的byte[]内容
* @throws IOException
*/
public static byte[] loadBytes(File file) throws IOException {
if (file == null || !file.exists()) {
return null;
}
byte[] result = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
result = loadBytes(fileInputStream);
} finally {
closeStream(fileInputStream);
}
return result;
}
7、从asset中获取文件
/**
* 从Asset中读取图片内容
*
* @param context
* @param drawableFile
* @return Bitmap
*/
public static Bitmap loadAssetDrawable(Context context, String drawableFile) {
if (TextUtils.isEmpty(drawableFile)) {
return null;
}
Bitmap result = null;
InputStream dataStream = null;
try {
dataStream = context.getAssets().open(drawableFile);
result = BitmapFactory.decodeStream(dataStream);
} catch (Throwable e) {
Log.w(LOG_TAG, e);
} finally {
IOUtilities.closeStream(dataStream);
}
return result;
}
/**
* 从Asset中读取文件内容,返回String
*
* @param context
* @param fileName
* @return
*/
public static String loadFromAssets(Context context, String fileName) {
if (TextUtils.isEmpty(fileName)) {
return "";
}
try {
return loadContent(context.getAssets().open(fileName), UTF8);
} catch (Exception e) {
Log.e(e.toString());
return "";
}
}
public static String loadFromAssets(Context context, String fileName, String encoding) {
if (TextUtils.isEmpty(fileName)) {
return "";
}
try {
loadContent(context.getAssets().open(fileName), encoding);
} catch (Exception e) {
Log.e(LOG_TAG, e);
}
return "";
}
public static void writeBundleToStream(Bundle data, OutputStream stream) throws IOException {
final Parcel parcel = Parcel.obtain();
data.writeToParcel(parcel, 0);
stream.write(parcel.marshall());
parcel.recycle();
}
public static Bundle readBundleFromStream(InputStream stream) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(stream, out);
Parcel parcel = Parcel.obtain();
byte[] data = out.toByteArray();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0);
Bundle bundle = new Bundle();
bundle.readFromParcel(parcel);
parcel.recycle();
return bundle;
}
public static InputStreamReader newUtf8OrDefaultInputStreamReader(InputStream stream) {
try {
return new InputStreamReader(stream, UTF8);
} catch (UnsupportedEncodingException e) {
return new InputStreamReader(stream);
}
}
public static OutputStreamWriter newUtf8OrDefaultOutputStreamWriter(OutputStream stream) {
try {
return new OutputStreamWriter(stream, UTF8);
} catch (UnsupportedEncodingException e) {
return new OutputStreamWriter(stream);
}
}
与Bitmap相关的工具类
/**
* 读取app文件的内容,同时解析为Bitmap类型
*
* @param context 上下文环境,可以是appContext,也可以是activity等
* @param filename 文件名
* @return
*/
public static Bitmap loadBitmap(Context context, String filename) {
if (context == null || TextUtils.isEmpty(filename)) {
return null;
}
Log.d(LOG_TAG, "loadDrawable filename: %s", filename);
FileInputStream inputStream = null;
try {
inputStream = context.openFileInput(filename);
return BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
Log.e(LOG_TAG, e);
} finally {
closeStream(inputStream);
}
return null;
}
public static void saveRightAngleImage(File rawPhoto, File destPhoto, int destWidth, int destHeight) {
if (rawPhoto == null || !rawPhoto.exists() || destPhoto == null) {
return;
}
String rawPhotoPath = rawPhoto.getAbsolutePath();
Bitmap bitmap = null;
try {
bitmap = rotateImage(getImageDegree(rawPhotoPath), rawPhotoPath, destWidth, destHeight);
if (bitmap == null) {
return;
}
// save the rotated image to file
IOUtilities.saveToFile(destPhoto, bitmap);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bitmap != null) {
bitmap.recycle();
}
}
}
private static int getImageDegree(String photoPath) throws Exception {
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int degree = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
case ExifInterface.ORIENTATION_NORMAL:
degree = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
Log.d(LOG_TAG, "orientation: %s, degree: %s", orientation, degree);
return degree;
}
private static Bitmap rotateImage(int degree, String imagePath, int destWidth, int destHeight) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, opt);
// calculate inSampleSize
opt.inSampleSize = calculateInSampleSize(opt, destWidth, destHeight);
opt.inJustDecodeBounds = false;
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
Bitmap rawBitmap = BitmapFactory.decodeFile(imagePath, opt);
Bitmap destBitmap = rawBitmap;
if (degree > 0 && rawBitmap != null) {
Matrix matrix = new Matrix();
if (rawBitmap.getWidth() > rawBitmap.getHeight()) {
matrix.setRotate(degree);
destBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawBitmap.getWidth(), rawBitmap.getHeight(),
matrix, true);
rawBitmap.recycle();
}
}
return destBitmap;
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
9、对文件的压缩和解压缩
public static void saveZipFile(InputStream inputStream, File destFile) throws IOException {
if (inputStream == null || destFile == null) {
throw new IOException("inputStream or destFile is null.");
}
FileOutputStream output = null;
output = new FileOutputStream(destFile);
byte[] buffer = new byte[1024 * 8];
BufferedInputStream in = new BufferedInputStream(inputStream, 1024 * 8);
BufferedOutputStream out = new BufferedOutputStream(output, 1014 * 8);
int len;
try {
while ((len = in.read(buffer, 0, 1024 * 8)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
out.close();
in.close();
}
}
/**
* 对文件解压缩
* // * @param zipFile
*
* @param outputDirectory
* @throws ZipException
* @throws IOException
*/
public static void upzip(File zipFile, String outputDirectory)
throws Exception {
ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile.getPath()));
ZipEntry z;
String name = "";
String extractedFile = "";
int counter = 0;
while ((z = in.getNextEntry()) != null) {
name = z.getName();
Log.d(LOG_TAG, "unzipping file: " + name);
if (z.isDirectory()) {
Log.d(LOG_TAG, name + "is a folder");
// get the folder name of the widget
name = name.substring(0, name.length() - 1);
File folder = new File(outputDirectory + File.separator + name);
folder.mkdirs();
if (counter == 0) {
extractedFile = folder.toString();
}
counter++;
Log.d(LOG_TAG, "mkdir " + outputDirectory + File.separator + name);
} else {
Log.d(LOG_TAG, name + "is a normal file");
File file = new File(outputDirectory + File.separator + name);
file.createNewFile();
// get the output stream of the file
FileOutputStream out = new FileOutputStream(file);
int ch;
byte[] buffer = new byte[1024];
// read (ch) bytes into buffer
while ((ch = in.read(buffer)) != -1) {
// write (ch) byte from buffer at the position 0
out.write(buffer, 0, ch);
out.flush();
}
out.close();
}
}
in.close();
}
10、获取文件中json内容
/**
* 读取json文件
*
* @param jsonPath
* @return
*/
public static String readJsonFile(String jsonPath) {
File file = new File(jsonPath);
Scanner scanner = null;
StringBuilder buffer = new StringBuilder();
try {
scanner = new Scanner(file, "utf-8");
while (scanner.hasNextLine()) {
buffer.append(scanner.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} finally {
if (scanner != null) {
scanner.close();
}
}
return buffer.toString();
}