Skip to content

Instantly share code, notes, and snippets.

@vlazzle
Created August 13, 2015 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlazzle/57128871f53ff55f3c2d to your computer and use it in GitHub Desktop.
Save vlazzle/57128871f53ff55f3c2d to your computer and use it in GitHub Desktop.
package com.twitter.externalstorage;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
private static final String TAG = "WES";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
copyToStorage();
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
copyToStorage();
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
}
}
}
private void copyToStorage() {
final File sourceDir = getExternalFilesDir(null);
final String identifier = "hello";
final File sourceFile = new File(sourceDir, identifier);
try {
FileOutputStream fileOutputStream = new FileOutputStream(sourceFile);
fileOutputStream.write("hello contents".getBytes());
} catch (IOException e) {
Log.d(TAG, "failed to create src file");
}
if (sourceFile.exists()) {
Log.d(TAG, "src: " + sourceFile.toString());
} else {
throw new IllegalStateException("src file doesn't exist");
}
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
final String destFile = getDestFile();
Log.d(TAG, "dest: " + destFile);
return copyFile(sourceFile, new File(destFile));
}
@Override
protected void onPostExecute(Boolean success) {
final String result = success ? "success" : "failure";
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}.execute();
}
private String getDestFile() {
final File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
baseDir.mkdirs();
return (new StringBuffer())
.append(baseDir.toString())
.append(File.separator)
.append("hellocopy")
.toString();
}
private static boolean copyFile(File srcFile, File destFile) {
InputStream inStream = null;
try {
inStream = new FileInputStream(srcFile);
return copyToFile(inStream, destFile);
} catch (FileNotFoundException e) {
Log.d(TAG, e.toString());
return false;
} finally {
closeSilently(inStream);
}
}
private static boolean copyToFile(InputStream is, File file) {
boolean success = false;
if (createPathForFile(file)) {
FileOutputStream out = null;
try {
// throws FileNotFoundException: open failed: EACCES (Permission denied)
out = new FileOutputStream(file);
final int bytesLen = readFullyWriteTo(is, out, 4 * 1024);
success = bytesLen != 0;
out.flush();
} catch (IOException e) {
Log.d(TAG, e.toString());
} finally {
closeSilently(out);
if (!success) {
// noinspection ResultOfMethodCallIgnored
file.delete();
}
}
}
return success;
}
private static boolean createPathForFile(File file) {
final File dir = file.getParentFile();
return dir == null || dir.exists() || dir.mkdirs();
}
private static int readFullyWriteTo(InputStream is, OutputStream os,
int bufferSize) throws IOException {
final byte[] buf = new byte[bufferSize];
int bytesRead;
int totalBytes = 0;
while ((bytesRead = is.read(buf)) != -1) {
if (os != null) {
os.write(buf, 0, bytesRead);
}
totalBytes += bytesRead;
}
return totalBytes;
}
private static void closeSilently(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignore) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment