android中file檔案常見操作
阿新 • • 發佈:2019-02-07
檔案操作相關(SD讀取,byte轉化,上傳等):
public class FileUtil {
private static String TAG = "FileUtil";
/** 預設下載檔案地址. */
public static String downPathRootDir = File.separator + "download" + File.separator;
/** 預設下載圖片檔案地址. */
public static String downPathImageDir = File.separator + "download" + File.separator + "cache_images"
+ File.separator;
/** 預設下載檔案地址. */
public static String downPathFileDir = File.separator + "download" + File.separator + "cache_files"
+ File.separator;
/**
* 下載網路檔案到SD卡中.如果SD中存在同名檔案將不再下載
*
* @param url
* 要下載檔案的網路地址
* @return 下載好的本地檔案地址
*/
public static String downFileToSD(String url) {
InputStream in = null;
FileOutputStream fileOutputStream = null;
HttpURLConnection con = null;
String downFilePath = null;
try {
if (!isCanUseSD()) {
return null;
}
File path = Environment.getExternalStorageDirectory();
File fileDirectory = new File(path.getAbsolutePath() + downPathImageDir);
if (!fileDirectory.exists()) {
fileDirectory.mkdirs();
}
File f = new File(fileDirectory, getFileNameFromUrl(url));
if (!f.exists()) {
f.createNewFile();
} else {
// 檔案已經存在
if (f.length() != 0) {
return f.getPath();
}
}
downFilePath = f.getPath();
URL mUrl = new URL(url);
con = (HttpURLConnection) mUrl.openConnection();
con.connect();
in = con.getInputStream();
fileOutputStream = new FileOutputStream(f);
byte[] b = new byte[1024];
int temp = 0;
while ((temp = in.read(b)) != -1) {
fileOutputStream.write(b, 0, temp);
}
} catch (Exception e) {
if (D)
Log.d(TAG, "" + e.getMessage());
return null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (con != null) {
con.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return downFilePath;
}
/**
* 描述:通過檔案的網路地址從SD卡中讀取圖片,如果SD中沒有則自動下載並儲存.
*
* @param url
* 檔案的網路地址
* @param type
* 圖片的處理型別(剪下或者縮放到指定大小,參考AbConstant類)
* @param newWidth
* 新圖片的寬
* @param newHeight
* 新圖片的高
* @return Bitmap 新圖片
*/
public static Bitmap getBitmapFromSDCache(String url, int type, int newWidth, int newHeight) {
Bitmap bit = null;
try {
// SD卡是否存在
if (!isCanUseSD()) {
bit = getBitmapFormURL(url, type, newWidth, newHeight);
return bit;
}
// 檔案是否存在
File path = Environment.getExternalStorageDirectory();
File fileDirectory = new File(path.getAbsolutePath() + downPathImageDir);
File f = new File(fileDirectory, getFileNameFromUrl(url));
if (!f.exists()) {
downFileToSD(url);
return getBitmapFromSD(f, type, newWidth, newHeight);
} else {
if (D)
Log.d(TAG, "要獲取的圖片路徑為:" + f.getPath());
// 檔案存在
if (type == AppConstant.CUTIMG) {
bit = ImageUtil.cutImg(f, newWidth, newHeight);
} else {
bit = ImageUtil.scaleImg(f, newWidth, newHeight);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bit;
}
/**
* 描述:通過檔案的網路地址從SD卡中讀取圖片.
*
* @param url
* 檔案的網路地址
* @param type
* 圖片的處理型別(剪下或者縮放到指定大小,參考AbConstant類)
* @param newWidth
* 新圖片的寬
* @param newHeight
* 新圖片的高
* @return Bitmap 新圖片
*/
public static Bitmap getBitmapFromSD(String url, int type, int newWidth, int newHeight) {
Bitmap bit = null;
try {
// SD卡是否存在
if (!isCanUseSD()) {
return null;
}
// 檔案是否存在
File path = Environment.getExternalStorageDirectory();
File fileDirectory = new File(path.getAbsolutePath() + downPathImageDir);
File f = new File(fileDirectory, getFileNameFromUrl(url));
if (!f.exists()) {
return null;
} else {
// 檔案存在
if (type == AppConstant.CUTIMG) {
bit = ImageUtil.cutImg(f, newWidth, newHeight);
} else {
bit = ImageUtil.scaleImg(f, newWidth, newHeight);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bit;
}
/**
* 描述:通過檔案的本地地址從SD卡讀取圖片.
*
* @param file
* the file
* @param type
* 圖片的處理型別(剪下或者縮放到指定大小,參考AbConstant類)
* @param newWidth
* 新圖片的寬
* @param newHeight
* 新圖片的高
* @return Bitmap 新圖片
*/
public static Bitmap getBitmapFromSD(File file, int type, int newWidth, int newHeight) {
Bitmap bit = null;
try {
// SD卡是否存在
if (!isCanUseSD()) {
return null;
}
// 檔案是否存在
if (!file.exists()) {
return null;
}
// 檔案存在
if (type == AppConstant.CUTIMG) {
bit = ImageUtil.cutImg(file, newWidth, newHeight);
} else {
bit = ImageUtil.scaleImg(file, newWidth, newHeight);
}
} catch (Exception e) {
e.printStackTrace();
}
return bit;
}
/**
* 描述:將圖片的byte[]寫入本地檔案.
*
* @param imgByte
* 圖片的byte[]形勢
* @param fileName
* 檔名稱,需要包含字尾,如.jpg
* @param type
* 圖片的處理型別(剪下或者縮放到指定大小,參考AbConstant類)
* @param newWidth
* 新圖片的寬
* @param newHeight
* 新圖片的高
* @return Bitmap 新圖片
*/
public static Bitmap getBitmapFormByte(byte[] imgByte, String fileName, int type, int newWidth, int newHeight) {
FileOutputStream fos = null;
DataInputStream dis = null;
ByteArrayInputStream bis = null;
Bitmap b = null;
try {
if (imgByte != null) {
File sdcardDir = Environment.getExternalStorageDirectory();
String path = sdcardDir.getAbsolutePath() + downPathImageDir;
File file = new File(path + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
int readLength = 0;
bis = new ByteArrayInputStream(imgByte);
dis = new DataInputStream(bis);
byte[] buffer = new byte[1024];
while ((readLength = dis.read(buffer)) != -1) {
fos.write(buffer, 0, readLength);
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
fos.flush();
}
b = getBitmapFormURL("/" + fileName, type, newWidth, newHeight);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (Exception e) {
}
}
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
}
return b;
}
/**
* 描述:根據URL從互連網獲取圖片.
*
* @param url
* 要下載檔案的網路地址
* @param type
* 圖片的處理型別(剪下或者縮放到指定大小,參考AbConstant類)
* @param newWidth
* 新圖片的寬
* @param newHeight
* 新圖片的高
* @return Bitmap 新圖片
*/
public static Bitmap getBitmapFormURL(String url, int type, int newWidth, int newHeight) {
Bitmap bit = null;
try {
bit = ImageUtil.getBitmapFormURL(url, type, newWidth, newHeight);
} catch (Exception e) {
if (D)
Log.d(TAG, "下載圖片異常:" + e.getMessage());
}
if (D)
Log.d(TAG, "返回的Bitmap:" + bit);
return bit;
}
/**
* 描述:獲取src中的圖片資源.
*
* @param src
* 圖片的src路徑,如(“image/arrow.png”)
* @return Bitmap 圖片
*/
public static Bitmap getBitmapFormSrc(String src) {
Bitmap bit = null;
try {
bit = BitmapFactory.decodeStream(FileUtil.class.getResourceAsStream(src));
} catch (Exception e) {
if (D)
Log.d(TAG, "獲取圖片異常:" + e.getMessage());
}
if (D)
Log.d(TAG, "返回的Bitmap:" + bit);
return bit;
}
/**
* 描述:獲取網路檔案的大小.
*
* @param Url
* 圖片的網路路徑
* @return int 網路檔案的大小
*/
public static int getContentLengthFormUrl(String Url) {
int mContentLength = 0;
try {
URL url = new URL(Url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
mHttpURLConnection.setConnectTimeout(5 * 1000);
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setRequestProperty("Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
mHttpURLConnection.setRequestProperty("Referer", Url);
mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
mHttpURLConnection.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
mHttpURLConnection.connect();
if (mHttpURLConnection.getResponseCode() == 200) {
// 根據響應獲取檔案大小
mContentLength = mHttpURLConnection.getContentLength();
}
} catch (Exception e) {
e.printStackTrace();
if (D)
Log.d(TAG, "獲取長度異常:" + e.getMessage());
}
return mContentLength;
}
/**
* HTTP檔案上傳.
*
* @param actionUrl
* 要使用的URL
* @param params
* 表單引數
* @param files
* 要上傳的檔案列表
* @return http返回的結果 或http響應碼
* @throws com.bslee.MeSport.global.AppException
* the ab app exception
*/
public static String postFile(String actionUrl, HashMap<String, String> params, HashMap<String, File> files)
throws AppException {
// 標識每個檔案的邊界
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--";
String LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
HttpURLConnection conn = null;
DataOutputStream outStream = null;
String retStr = "200";
try {
URL uri = new URL(actionUrl);
conn = (HttpURLConnection) uri.openConnection();
// 允許輸入
conn.setDoInput(true);
// 允許輸出
conn.setDoOutput(true);
conn.setUseCaches(false);
// Post方式
conn.setRequestMethod("POST");
// 設定request header 屬性
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 組裝表單引數資料
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
// 獲取連線傳送引數資料
outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 傳送檔案資料
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\""
+ LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
// 請求頭結束至少有一個空行(即有兩對\r\n)表示請求頭結束了
if (D)
Log.d("TAG", "request start:" + sb1.toString());
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
// 一個檔案結束一個空行
outStream.write(LINEND.getBytes());
}
// 請求結束的邊界列印
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
Log.d("TAG", "request end:" + new String(end_data).toString());
outStream.write(end_data);
outStream.flush();
outStream.close();
// 獲取響應碼
int ret = conn.getResponseCode();
retStr = String.valueOf(ret);
if (ret == 200) {
String result = StrUtil.convertStreamToString(conn.getInputStream());
return result;
}
} catch (Exception e) {
throw new AppException(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return retStr;
}
/**
* 獲取檔名,通過網路獲取,如果網路失敗擷取檔案地址URL作為檔名,獲取的是最後一個“/”以後的字串.
*
* @param strUrl
* 檔案地址
* @return 檔名
*/
public static String getFileNameFromUrl(String strUrl) {
String name = null;
try {
if (StrUtil.isEmpty(strUrl) || strUrl.indexOf("/") == -1 || strUrl.length() < 2) {
URL url = new URL(strUrl);
HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
mHttpURLConnection.setConnectTimeout(5 * 1000);
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setRequestProperty("Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
mHttpURLConnection.setRequestProperty("Referer", strUrl);
mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
mHttpURLConnection.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
mHttpURLConnection.connect();
if (mHttpURLConnection.getResponseCode() == 200) {
for (int i = 0;; i++) {
String mine = mHttpURLConnection.getHeaderField(i);
if (mine == null) {
break;
}
if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
if (m.find())
return m.group(1);
}
}
// 預設取一個檔名
return DateUtil.getCurrentDate(DateUtil.dateFormatYMDHMS) + ".tmp";
}
return null;
} else {
int index = strUrl.lastIndexOf("/");
name = strUrl.substring(index + 1);
}
} catch (Exception e) {
}
return name;
}
/**
* 描述:從sd卡中的檔案讀取到byte[].
*
* @param path
* sd卡中檔案路徑
* @return byte[]
*/
public static byte[] getByteArrayFromSD(String path) {
byte[] bytes = null;
ByteArrayOutputStream out = null;
try {
File file = new File(path);
// SD卡是否存在
if (!isCanUseSD()) {
return null;
}
// 檔案是否存在
if (!file.exists()) {
return null;
}
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
return null;
}
FileInputStream in = new FileInputStream(path);
out = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = in.read(buffer)) != -1) {
out.write(buffer, 0, size);
}
in.close();
bytes = out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
}
return bytes;
}
/**
* 描述:將byte陣列寫入檔案.
*
* @param path
* the path
* @param content
* the content
* @param create
* the create
*/
public static void writeByteArrayToSD(String path, byte[] content, boolean create) {
FileOutputStream fos = null;
try {
File file = new File(path);
// SD卡是否存在
if (!isCanUseSD()) {
return;
}
// 檔案是否存在
if (!file.exists()) {
if (create) {
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
file.createNewFile();
}
} else {
return;
}
}
fos = new FileOutputStream(path);
fos.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
}
}
/**
* 描述:SD卡是否能用.
*
* @return true 可用,false不可用
*/
public static boolean isCanUseSD() {
try {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 描述:獲取預設的圖片儲存全路徑.
*
* @return the default image down path dir
*/
public static String getDefaultImageDownPathDir() {
String pathDir = null;
try {
if (!isCanUseSD()) {
return null;
}
// 初始化圖片儲存路徑
File fileRoot = Environment.getExternalStorageDirectory();
File dirFile = new File(fileRoot.getAbsolutePath() + FileUtil.downPathImageDir);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
pathDir = dirFile.getPath();
} catch (Exception e) {
}
return pathDir;
}
}