我只是想将文件从网址http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true下载到我的系统,这里是我的代码
getDirectory=(Button)findViewById(R.id.btn_newDirectory);
getDirectory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
new DownloadingTask().execute();
}
});
private class DownloadingTask extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection)
url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream("/Users/Documents");
Log.i("Download","complete");
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
}
文件未下载但丢失错误下载错误异常/用户/文档(没有此类文件或目录)
答案 0 :(得分:2)
没有&#34;用户/文件&#34;存储上的目录。让我稍微重写你的代码
getDirectory=(Button)findViewById(R.id.btn_newDirectory);
getDirectory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
new DownloadingTask().execute();
}
});
private class DownloadingTask extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection)
url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(new File(getFilesDir(),"Roboto-Regular.ttf")); // File you want to save to, It creates Roboto-Regular.ttf in your Internal Storage you got from "getFilesDir() method
Log.i("Download","complete");
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}}
此代码会将字体下载到您应用的内部存储空间中。如果您想将其保存到外部存储设备或获取更多信息,您可以试一试这篇文章: https://developer.android.com/training/basics/data-storage/files.html