Ted pottel
Ted pottel

Reputation: 6983

Is there a fast way to copy files to sdcard

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;
}

Upvotes: 0

Views: 794

Answers (2)

La bla bla
La bla bla

Reputation: 8708

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

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006614

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

Upvotes: 2

Related Questions