0

I have a function to copy a jpeg stored in assets to the sd card. It works, but very very slow. The averg file size is around 600k . Is there a better way to do this, code:

void SaveImage(String from, String to) throws IOException {
  // opne file from asset
  AssetManager assetManager = getAssets();
  InputStream inputStream;
  try {
    inputStream = assetManager.open(from);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
  }

  // Open file in sd card
  String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
  OutputStream outStream = null;
  File file = new File(extStorageDirectory, to);
  try {
    outStream = new FileOutputStream(file);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
    return;
  }

  int c;
  while ((c = inputStream.read()) != -1) {
    outStream.write(c);
  }

  outStream.close();
  inputStream.close();
  return;
}
Jano
  • 62,815
  • 21
  • 164
  • 192
Ted pottel
  • 6,869
  • 21
  • 75
  • 134

2 Answers2

2

Read and write more than one character at a time. 16KB is probably a reasonable buffer size, though feel free to experiment.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • @Tedpottel: See the accepted answer in http://stackoverflow.com/questions/4447477/android-how-to-copy-files-in-assets-to-sdcard – CommonsWare Sep 18 '12 at 15:47
0

You should try reading and writing using a Buffer Classes BufferedInputStream and BufferedOutputStream

InputStream inputStream;
BufferedInputStream bis;
try {
    inputStream = assetManager.open(from);
    bis = new BufferedInputStream(inputStream);
} catch (IOException e) {
...
...
try {
    outStream = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
...
...
    while ((c = bis.read()) != -1) {
    ...
    }
...
...

bis.close();

Good luck

La bla bla
  • 8,558
  • 13
  • 60
  • 109
  • Hi,Wow what a diffrence in speed, I thought it was going to be more complicated then this to speed it up :) – Ted pottel Sep 19 '12 at 15:44