我正在尝试在我的Android应用中完成两件事:
我的问题是,如何从服务器下载文件并将其显示在我的应用程序中?
我的下载代码如下:
public void downloadFiles () {
try {
URL url = new URL ("http://google.com/nexuspads.png");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/" ;
Log.v ("LOG_TAG" , "PATH: " + PATH);
File file = new File (PATH);
file.mkdirs();
String fileName = "image.png";
File outputFile = new File (file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
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 (IOException e) {
Log.d ("LOG_TAG2 ", "Error " + e );
// Toast.makeText(,"error " +e.toString(), Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
要列出文件夹中的文件,可按以下步骤进行操作..
String path = Environment.getExternalStorageDirectory().toString()+"/YOUR folder here/";
File f = new File(path);
final File listfile[] = f.listFiles();
String[] fileList = new String[listfile.length];
for (int i=0; i < listfile.length; i++)
{
fileList[i] = listfile[i].getName();
Log.v("Files", "FileName:" + listfile[i].getName());
}
然后,您可以在Alert Dialog或ListView中显示结果。