0
我知道這已經在這裏問了幾次,但我不知道我該走哪條路。這段代碼可以下載html文件,但是在嘗試將html寫入文件時會出現IOException。我已經嘗試了許多關於sof的建議,但似乎沒有一個適用於我,因此我似乎覺得它應該有效。如何將html寫入Android中的文件
class Downloader extends AsyncTask<URL, Void, Void> {
String site = getResources().getString(R.string.sched_hd_url);
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/directory/");
File file = new File(dir, "file.html");
@Override
protected Void doInBackground(URL... urls) {
try {
URL url = new URL(site);
URLConnection yc = url.openConnection();
BufferedInputStream in = new BufferedInputStream(new URL(site).openStream());
OutputStream out = new FileOutputStream(file);
int total = 0;
int count;
byte data1[] = new byte[1024];
while ((count = in.read(data1)) != -1) {
out.write(data1);
total += count;
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
progress.setVisibility(View.INVISIBLE);
finish();
}
}
我運行此代碼,沒有文件出現在我指定的目錄中。該目錄已經存在,而且我的清單中有權限。任何建議將不勝感激。
嘗試out.flush()? –
您還需要'finally'子句中的'out.close()'! – ChuongPham
下面是一個簡單的檢查:手機是否被連接到它的計算機安裝(即正在使用)? (我知道這聽起來像一個愚蠢的檢查,但這已經讓我絆倒了)。也就是說,如果您的外部存儲目錄已安裝並可從PC訪問,那麼很有可能您的PC已鎖定您的應用程序(和您的手機)訪問外部存儲。 (注意:這真是一個瘋狂的猜測,我可以離開..) – RichS