假設從資料庫取出的一個字串物件為:
String picPath = "aaa\bbb\ccc\photo1.png";//將"\"替換為"/"後為網路上某一個圖片檔案的相對路徑
請問要如何把字串中的"\"全部更換成"/"以利後續程式的撰寫呢?
通常大家第一個想到的程式寫法是:String picPath2 = picPath.replaceAll("\","/");
但是這樣的寫法在Eclipse中編譯並不會通過,找了資料才想起是java正規表示式的緣故;大家猜猜到底要寫幾個"\"和"/"才正確?
正確的寫法為:String picPath2 = picPath.replaceAll("\\\\","/");
轉換完之後要開始做字串切割的工作,可能有人有疑問為什麼不直接把picPath做字串切割就好?這當然是有緣故的,後面再繼續介紹。
為了避免產生不必要的exception,可先加個if/else判斷式在進行字串分割的動作:
if(picPath2.indexOf("/")!= -1){
String[] picPath3 = picPath.split("/");
}
分割完之後,準備在手機中建立資料夾,以利圖片的存取,在此整合前面的程式碼建立資料夾:
String picPathInDB = "aaa\bbb\ccc\photo1.png";//此為從資料庫中取出的字串
String picPath = picPathInDB.replaceAll("\\\\","/");//將"\"更換為"/"
String picInPhonePath = "/data/data/android.testProject.project/"//此為資料在手機中存取的路徑
File filePhotoPath=new File(picInPhonePath+photoPath[0]+"/"+photoPath[1]+"/"+photoPath[2]);//建立資料夾
if(!filePhotoPath.exists()){//如果資料夾不存在
filePhotoPath.mkdirs();//建立資料夾
}
資料夾建立之後就可以將圖片從網路上下載之後按照資料庫中的路徑存放在手機中,並且將圖片轉成Bitmap讓手機可以使用。
資料夾正確的建立之後,才能將圖片依照資料庫中的相對路徑存在手機的資料夾中;假設某圖片的相對路徑為:aaa/bbb/ccc/ddd.png,則此圖片存放在手機的路徑就是為:picInPhonePath +"aaa/bbb/ccc/ddd.png",也就是picInPhonePath +picPath 。
前面有提到為什麼要將"\"一次全部取代變為"/"呢?因為這樣可以方便讓我們直接存取圖片在網路上的位置,並將圖片下載至剛剛建立好的資料夾中:
URL imgUrl = new URL("http://www.test.com.tw/" + picPath);
/*如果沒有將"\"變成"/",則上行程式碼會變成:
URL imgUrl = new URL("http://www.test.com.tw/" + photoPath[0]+"/"+photoPath[1]+"/"+photoPath[2]+"/"+photoPath[3]);*/
URLConnection imageConn = imgUrl.openConnection();
imageConn.connect();
InputStream imageOnCloud = imageConn.getInputStream();
String outFileName = picInPhonePath + picPath;
OutputStream imageInPhone = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = imageOnCloud.read(buffer)) > 0) {
imageInPhone.write(buffer, 0, length);
imageInPhone.flush();
imageInPhone.close();
imageOnCloud.close();
Bitmap bitmap = BitmapFactory.decodeFile(picInPhonePath + picPath);
因為下載需要時間,建議可搭配ProgressBar與Handler一起使用在UI中,可以參考我的另一篇網誌。而若要從一個txt檔案做大量字串分割的工作,可參考此篇網誌。
0 comments:
Post a Comment