我想从网址下载文本文件并将其保存在设备本地并在我的应用中使用。
代码:
try {
File file = new File(getFilesDir(), "file.txt");
if (file.length() > 0) {
//File already exists and it is not empty
return;
}
URL url = new URL("https://www.abc.com/file.txt");
FileOutputStream fos = new FileOutputStream(file);
InputStream in = url.openStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
} catch (Exception e) {
// TODO:
}
正如您所看到的,代码与getFilesDir()
一致,假设始终存在。但是,通过适当的网络连接和权限,几乎没有问题:
getFilesDir()
假设在任何情况下都失败了吗?修改 当我尝试读取我在logcat中显示的下载文件(有时会发生在10中)时,我得到的是内容:
读取文件的代码:
BufferedReader inputReader= = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
Log.e("inputString: ", inputString);
}
inputReader.close();
谢谢
答案 0 :(得分:2)
我的getFilesDir()假设在任何情况下都失败了吗?
根据documentation,它应始终无需任何权限。
是否存在任何文件未下载/错误内容等的情况.., 用这个代码?
当然,我的意思是只是一个简单的连接丢失会导致下载失败,还有很多其他的东西可能会出错,比如缺少必要的权限( android.permission.INTERNET ),错误的编码,磁盘已满,。 ..
一旦遇到文件下载但已全部编码的问题 人物,无论我多么下载它,它仍然有 相同的编码文本。只有当我重新安装我的应用程序时,才适当 文字已下载。从那时起,从未遇到过这个问题。任何原因 对于那种奇怪的行为?
这可能是编码问题,将FileOutputStream包装在OutputStreamWriter中,这允许您在构造函数中传递编码参数。
Writer writer = new OutputStreamWriter(fos);
.
.
.
writer.write(buffer, 0, length);
答案 1 :(得分:1)
以下示例可能会有所帮助:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
答案 2 :(得分:0)
这不是一个答案,而是一个建议,使用ion Android网络库。
来自例子:
Ion.with(context)
.load("http://example.com/really-big-file.zip")
// have a ProgressBar get updated automatically with the percent
.progressBar(progressBar)
// and a ProgressDialog
.progressDialog(progressDialog)
// can also use a custom callback
.progress(new ProgressCallback() {@Override
public void onProgress(int downloaded, int total) {
System.out.println("" + downloaded + " / " + total);
}
})
.write(new File("/sdcard/really-big-file.zip"))
.setCallback(new FutureCallback<File>() {
@Override
public void onCompleted(Exception e, File file) {
// download done...
// do stuff with the File or error
}
});
所有操作都不在UI线程中完成,因此用户始终可以看到响应式应用程序。
答案 3 :(得分:0)
我无法评论您的案例中出现的问题,我会发布一段代码片段,用于检测我定位的文件类型然后获取它。这对我来说总是如预期的那样。我修改了我的&#34; onPostExecute&#34;在这里适合我的答案的方法,我试图保持我的变量的名称与你的相似。我省略了下载进度指示栏以简化代码段。下载必须在后台完成,因此&#34; AsyncTask&#34;用来。对于代码段,我使用谷歌的随机文本文件。
final String file_url = "https://www.kernel.org/doc/Documentation/power/drivers-testing.txt";
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(file_url);
final String fileName = URLUtil.guessFileName(file_url, null, fileExtension);
final String path = Environment.getExternalStorageDirectory().toString() + "/" + fileName;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(file_url);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream in = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path);
byte buffer[] = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
in.close();
} catch (IOException e) {
Log.e("Downloading file", "Download Error", e);
}
return null;
}
@Override
public void onPostExecute(Void result) {
try {
File file = new File(path);
BufferedReader inputReader = new BufferedReader(new FileReader(file));
String inputString;
while ((inputString = inputReader.readLine()) != null) {
Log.e("inputString: ", inputString);
}
inputReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.execute();
答案 4 :(得分:0)
尝试使用以下代码:
public void downloadFile(){
String DownloadUrl = "Paste Url to download a text file here…";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
request.setDescription("sample text file for testing"); //appears the same in Notification bar while downloading
request.setTitle("Sample.txt");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui","com.android.providers.downloads.ui.DownloadList");
List <resolveinfo> list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}