簡體   English   中英

如何從互聯網將文件寫入SD卡?

[英]How to write files to an SD Card from the internet?

一個例子就是一個簡單的圖像。

我已經嘗試了很多事情,盡管有很多道理,但它只是拒絕工作。

到目前為止,我已經能夠抓取25張照片並將其添加到

/ sdcard /應用名稱/sub/dir/filename.jpg

它們都根據DDMS出現在此處,但文件大小始終為0。

我猜可能是因為我的輸入流?

這是我的功能,負責下載和保存。

public void DownloadPages()
{   
    for (int fileC = 0; fileC < pageAmount; fileC++)
    {

        URL url;
        String path = "/sdcard/Appname/sub/dir/";

        File file = new File(path, fileC + ".jpg");

        int size=0;
        byte[] buffer=null;

        try{
            url = new URL("http://images.bluegartr.com/bucket/gallery/56ca6f9f2ef43ab7349c0e6511edb6d6.png");
            InputStream in = url.openStream();

            size = in.available();  
            buffer = new byte[size];  
            in.read(buffer);  
            in.close();  
        }catch(Exception e){

        }

            if (!new File(path).exists())
                new File(path).mkdirs();

       FileOutputStream out;

       try{
           out = new FileOutputStream(file);
           out.write(buffer);  
           out.flush();  
           out.close();
       }catch(Exception e){

       }


    }

}

它只給我該目錄中的25個文件,但它們的文件大小均為零。 我不知道為什么。 這實際上與我在Java程序中使用的代碼相同。

PS ...

如果您要給我解決方案...我已經嘗試過這樣的代碼。 沒用

    try{
        url = new URL(urlString);
        in = new BufferedInputStream(url.openStream());
        fout = new FileOutputStream(filename);

        byte data[] = new byte[1024];
        int count;
        System.out.println("Now downloading File: " + filename.substring(0, filename.lastIndexOf(".")));
        while ((count = in.read(data, 0, 1024)) != -1){
            fout.write(data, 0, count);
        }
    }finally{
            System.out.println("Download complete.");
            if (in != null)
                    in.close();
            if (fout != null)
                    fout.close();
    }
}

這是我的目錄的圖像

http://oi48.tinypic.com/2cpcprm.jpg

改變第二個選項,嘗試以下方法,

byte data[] = new byte[1024];
long total = 0;

int count;

while ( ( count = input.read(data)) != -1 )
{
    total += count;
    output.write( data,0,count );
}

這與while語句中的while ((count = in.read(data, 0, 1024)) != -1)

使用番石榴應該是這樣的:

String fileUrl = "xxx";
File file = null;

InputStream in;
FileOutputStream out;
try {
  Uri url = new URI(fileUrl);
  in = url.openStream();
  out = new FileOutputStream(file)
  ByteStreams.copy(in, out);
} 
catch (IOException e) {
  System.out.println(e.toString());
}
finally {
  in.close();
  out.flush();
  out.close();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM