在 Android 應用中,我們經常需要從網絡上下載 js 和 css 文件,并在 WebView 中使用它們。為了更好地管理這些文件,我們可以將它們封裝為庫,以便于復用和維護。
下面是一個簡單的封裝示例,包含一個下載器和一個解壓器:
public class Downloader { public static void downloadFile(String url, String destPath) throws IOException { URLConnection conn = new URL(url).openConnection(); InputStream in = conn.getInputStream(); FileOutputStream out = new FileOutputStream(destPath); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >0) { out.write(buffer, 0, len); } out.close(); in.close(); } } public class Unzipper { public static void unzipFile(String zipPath, String destDir) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String entryName = entry.getName(); if (entry.isDirectory()) { File dir = new File(destDir, entryName); dir.mkdirs(); } else { File file = new File(destDir, entryName); FileOutputStream out = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >0) { out.write(buffer, 0, len); } out.close(); } } in.close(); } }
使用這些類,我們可以輕松地下載和解壓文件:
String jsUrl = "https://example.com/scripts.js"; String cssUrl = "https://example.com/styles.css"; String cacheDir = getApplicationContext().getCacheDir().toString(); try { Downloader.downloadFile(jsUrl, cacheDir + "/scripts.zip"); Unzipper.unzipFile(cacheDir + "/scripts.zip", cacheDir + "/scripts/"); } catch (IOException e) { e.printStackTrace(); }
除了下載和解壓,我們還可以添加緩存和錯誤處理機制,使我們的封裝更加健壯和可靠。
上一篇html 字間距代碼
下一篇eval與json