复制现有的png文件并以编程方式重命名

时间:2017-02-07 02:08:34

标签: java android bitmap fileoutputstream

我在SD卡上的“电影”文件夹中有一个png文件。我想复制并重命名该文件在同一文件夹中。我对如何正确调用SaveImage方法感到困惑。

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanningResult != null) {
        isbn = scanningResult.getContents();
        SaveImage();
    }
    else{
        Toast toast = Toast.makeText(getApplicationContext(),
                "No scan data received!", Toast.LENGTH_SHORT);
        toast.show();
    }
}


private void SaveImage(Bitmap finalBitmap){
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/Movies/");
    String fname = "Image-"+ isbn +".jpg";
    File file = new File (myDir, fname);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

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

3 个答案:

答案 0 :(得分:3)

我只是想复制同一个文件并将其重命名

感谢您让它更清晰。您可以使用它从source文件复制到destination文件。

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

答案 1 :(得分:1)

所以你的问题是,如何正确调用你的SaveImage(Bitmap finalBitmap)方法,对吧?当您的SaveImage方法获取Bitmap作为参数时,您需要将Bitmap作为参数发送。

您可以使用BitmapFactory从文件中创建Bitmap对象,并将此Bitmap对象发送到SaveImage方法:

String root = Environment.getExternalStorageDirectory().toString();
Bitmap bMap = BitmapFactory.decodeFile(root + "/Movies/myimage.png");
SaveImage(bMap);

答案 2 :(得分:1)

重命名文件:

File source =new File("abc.png");
File destination =new File("abcdef.png");
source.renameTo(destination);

复制文件:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

Path source=Paths.get("abc.png");
Path destination=Paths.get("abcdef.png");
Files.copy(source, destination);