Android學習筆記 - 下載、存儲篇

1.使用HTTP協議下載文件
 //創建URL鏈接
 URL url = new URL("
http://www.study.com/test.txt");
 
 //創建一個HttpURLConnection對象
 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 
 //獲得一個InputStream對象
 BufferReader reader = new BufferReader(new InputStreamReader(conn.getInputStream());
 
 //讀取內容(文本類型)
 String line = null;
 while((line = reader.readLine()) != null){
  System.out.println(line);
 }
 
2.將下載的文件寫入SDCARD
 //得到當前設備SD卡的目錄
 String SDCARD = Environment.getExternalStorageDirectory() + "/";
 
 //AndroidMainfest.xml中添加訪問互聯網和SD卡的權限
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 
 //下載文件
 URL url = new URL("http://...");
 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 InputStream fileStream = conn.getInputStream();
 
 //創建目錄
 File dir = new File(SDCARD + dirName);
 dir.mkdir();
 
 //創建文件
 File dir = new File(SDCARD + dirName + fileName);
 File file = dir.createNewFile();
 
 //寫入文件
 OutputStream stream = new FileOutputStream(file);
 byte buff[] = new byte[4 * 1024];
 while((fileStream.read(buff)) != -1){
  stream.write(buff);
 }
 stream.flush();
 stream.close();

 

//下載輔助類完整示例

public class DownloadHelper {

	// 獲取指定URL返回的文檔結果
	public static String downloadText(String navUrl) {
		BufferedReader reader = null;
		StringBuffer sb = null;
		String line = null;
		try {
			sb = new StringBuffer();
			reader = new BufferedReader(new InputStreamReader(getInputStream(navUrl)));
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			reader.close();
			return sb.toString();
		} catch (Exception err) {
			Log.e("Exception", err.getMessage());
			return null;
		}
	}

	// 從指定URL下載文件
	public static int downloadFile(String navUrl) {
		try {

			InputStream stream = getInputStream(navUrl);
			StorageHelper storage = new StorageHelper();
			return storage.writeFile("study/", navUrl.substring(navUrl.lastIndexOf("/")), stream);
		} catch (Exception err) {
			Log.e("Exception", err.getMessage());
			return -1;
		}
	}

	// 獲取指定URL的輸入流
	private static InputStream getInputStream(String navUrl) {
		try {
			URL url = new URL(navUrl);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			return http.getInputStream();
		} catch (Exception err) {
			Log.e("Exception", err.getMessage());
			return null;
		}
	}
}


//存儲輔助類完整示例

public class StorageHelper {
	private String SDCARD = null;

	// 構造函數,獲取SDCARD路徑
	public StorageHelper() {
		SDCARD = Environment.getExternalStorageDirectory() + "/";
	}

	// 屬性:SDCARD路徑
	public String getSDCardPath() {
		return SDCARD;
	}

	// 在SDCARD裏創建目錄
	public boolean createDirectory(String path) {
		File dir = new File(SDCARD + path);
		return dir.mkdir();
	}

	// 在SDCARD裏指定目錄創建新文件
	public File createFile(String path, String fileName) {
		try {
			File file = new File(SDCARD + path + fileName);
			if (file.createNewFile()) {
				return file;
			} else {
				return null;
			}
		} catch (Exception err) {
			Log.e("Exception", err.getMessage());
			return null;
		}
	}

	// 判斷SDCARD裏指定目錄中是否有指定名稱的文件
	public boolean isExistsFile(String path, String fileName) {
		File file = new File(SDCARD + path + fileName);
		return file.exists();
	}

	// 往SDCARD裏指定目錄、指定名稱寫入流
	public int writeFile(String path, String fileName, InputStream fileStream) {
		OutputStream writer = null;
		try {
			createDirectory(path); // 不管3721,先創建目錄

			if (!isExistsFile(path, fileName)) { // 判斷文件是否存在
				File file = createFile(path, fileName);
				writer = new FileOutputStream(file);
				byte[] data = new byte[4 * 1024];
				while (fileStream.read(data) != -1) {
					writer.write(data);
				}
				writer.flush();
				writer.close();
				return 1;
			} else {
				return 0;
			}
		} catch (Exception err) {
			Log.e("Exception", err.getMessage());
			return -1;
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章