java - 从服务器下载文件并放到/raw文件夹中

标签 java android

这是我想做的。我想制作一个应用程序,例如它有一个按钮,可以下载某个视频文件并将其放在资源(原始)文件夹中。可能吗?

最佳答案

简短回答:你不能

在任何情况下,您都不能在运行时将文件写入/转储到 raw/assets 文件夹。

您可以下载视频并将其存储到内部存储器(应用程序保留存储)或外部存储器(通常是您的SDC卡))

例如,您可以将媒体文件(例如位图)存储到外部存储中,如下所示。

 private void saveAnImageToExternalMemory(Bitmap finalBitmap) {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    String fname = "yourimagename.jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}

同样,从外部内存读取一个文件,在本例中是一个图像(然后加载到 imageView)

private void loadImageFromStorage(String path){
    try {
        File f=new File(path, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView img=(ImageView)findViewById(R.id.imgPicker);
        img.setImageBitmap(b);
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

编辑:此外,您可以将数据存储到内存中

Alternatively you can also save the Bitmap to the internal storage in case the SD card is not available or for whatever other reasons you may have. Files saved to the internal storage are only accessible by the application which saved the files. Neither the user nor other applications can access those files

public boolean saveImageToInternalStorage(Bitmap image) {
    try {
        FileOutputStream fos = context.openFileOutput("yourimage.png", Context.MODE_PRIVATE);
        // Writing the bitmap to the output stream
        image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
        return true;
    } catch (Exception e) {
        Log.e("saveToInternalStorage()", e.getMessage());
        return false;
    }
}

Check this documentation for more information

问候,

关于java - 从服务器下载文件并放到/raw文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38722816/

相关文章:

java - String.class 在 Camel-Context 中拆分使用

java - 如何在 Retrofit2 中正确处理重定向作为响应

android - 抛出 Google Awareness API SecurityException

android - 将文本顶部和底部与 2 个 TextView 对齐

java - 每个 JVM 或每个 CPU 核心的线程数

java - 此处理程序类应该是静态的,否则可能会发生泄漏 : final Handler

java - Jackson 无法反序列化为 ForeignCollection (Ormlite)

javascript - Phonegap 3 上有 onExit 或 onDestroy 方法吗?

PST 时区的 Java 日历错误时间?

android - 安卓中的VSYNC是什么