我正在尝试从服务器下载几个文本文件。它们都具有相似的名称(例如 text1.txt、txt2.txt),但编号不同(每月更改数量)。我似乎无法下载文件。Java 一直告诉我它遇到了一个找不到文件的错误/异常。有谁知道我怎么能克服这个?
下载类。
public class downloadText extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... params) {
try {
File sourceLocation = new File(targetPath);
sources = sourceLocation.listFiles();
Arrays.sort(sources);
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "aiyo/edition/text/");
if (dir.exists() == false) {
dir.mkdirs();
}
Log.d("param", params[0]);
URL url = new URL("http://create.aiyomag.com/assets/app_mag/ALYO/9_1342080926/text"); // you can write here any link
URLConnection connection = url.openConnection();
connection.connect();
int contentLength=connection.getContentLength();
// get file name and file extension
String fileExtenstion = MimeTypeMap
.getFileExtensionFromUrl(params[0]);
String name = URLUtil.guessFileName(params[0], null,
fileExtenstion);
File file = new File(dir, name);
Log.d("File in content","The file is "+file.getName());
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
OutputStream fos = new FileOutputStream(file);
/*
* Read bytes to the Buffer until there is nothing more to
* read(-1).
*/
int lenghtOfFile = connection.getContentLength();
int total = 0;
byte baf[] = new byte[1024];
int current = 0;
while ((current = bis.read(baf)) != -1) {
total += current;
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
mProgressDialog.setProgress(((total * 100) / lenghtOfFile));
fos.write(baf, 0, current);
}
// close every file stream
fos.flush();
fos.close();
is.close();
} catch (IOException e) {
Log.e("DownloadManager", "Error: " + e);
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
mProgressDialog.setProgress(Integer.parseInt(values[0]));
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// if (fileInteger == max) {
// dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
// return;
// }
Log.d("post execute", "i::" + fileInteger);
// fileInteger++;
// publishProgress("" + (int) ((fileInteger * 100) / max));
// mProgressDialog.setSecondaryProgress(((fileInteger * 100) / max));
String link = txturl;
downloadText = new downloadText();
downloadText.execute(link);
}
主要的。
btn_txt = (Button) findViewById(R.id.text);
btn_txt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String link;
link = txturl+fileInteger+".txt";
new Thread(new Runnable() {
public void run() {
max = (totalFile(pageNum) - 1);
text.post(new Runnable() {
public void run() {
text.setText("" + max);
}
});
}
}).start();
downloadText = new downloadText();
downloadText.execute(link);
}
});