I'm trying to copy some files from my App's internal folder to the external memory of an android device.
I'm using ACTION_OPEN_DOCUMENT_TREE for the user to select the desired destination folder, in 'to', and have a list of Uri for the files I want to copy 'from', what's the best way to do it?
I tried:
public void copyFiles(ArrayList <Uri>from, Uri to)
{
for (Uri u:from
) {
try {
File f = new File(u.getPath());
FileInputStream in = new FileInputStream(f);
File d = new File(to.getPath(), f.getName());
FileOutputStream out = new FileOutputStream(d);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
}
catch (Exception ex){
Log.e(TAG,ex.getLocalizedMessage());
}
}
}
But it throws an exception complaining the destination file does not exist: open failed: ENOENT (No such file or directory).
Am I missing some step?
Related
I try to read a pdf file store in the assets folder. I see this solution :
Read a pdf file from assets folder
But like comments say this it's not working anymore, the file cannot be found, is there another solution for read a pdf file directly, without copy pdf in external storage ?
And I don't want to use PdfRenderer my minimal API is 17
Maybe this can be helpful for somebody so I post my answer :
private void openPdf(String pdfName){
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), pdfName);
try
{
in = assetManager.open(pdfName);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/"+pdfName),
"application/pdf");
startActivity(intent);
}
The pdf file is store inside the assets folder
I'm implementing a file browser feature in my app. I know how to gain persistent permission for the external sd card using the ACTION_OPEN_DOCUMENT_TREE intent and how to create folders and delete files/folders using the DocumentFile class.
I can't however find a way to copy/move a file to an external sd card folder. Can you point me to the right direction ?
I have figured it out using lots of examples on SO. My solution for music files:
private String copyFile(String inputPath, String inputFile, Uri treeUri) {
InputStream in = null;
OutputStream out = null;
String error = null;
DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), treeUri);
String extension = inputFile.substring(inputFile.lastIndexOf(".")+1,inputFile.length());
try {
DocumentFile newFile = pickedDir.createFile("audio/"+extension, inputFile);
out = getActivity().getContentResolver().openOutputStream(newFile.getUri());
in = new FileInputStream(inputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
} catch (FileNotFoundException fnfe1) {
error = fnfe1.getMessage();
} catch (Exception e) {
error = e.getMessage();
}
return error;
}
I've been looking at this site for the past 3 or so hours. How to copy files from 'assets' folder to sdcard?
This is the best I could come up with because I'm only trying to copy one file at a time.
InputStream in = null;
OutputStream out = null;
public void copyAssets() {
try {
in = getAssets().open("aabbccdd.mp3");
File outFile = new File(root.getAbsolutePath() + "/testf0lder");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: ", e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
I've figured out how to create a file and save a text file. http://eagle.phys.utk.edu/guidry/android/writeSD.html
I would rather save an mp3 file to the sdcard rather than a text file.
When I use this code I provided, I get a text document that same size as the aabbccdd.mp3 file. It does not create a folder and save an .mp3 file. It saves a text document in the root folder. When you open it, I see a whole bunch of chinese letters, but at the top in English I can see the words WireTap. WireTap Pro was the program I used to record the sound so I know the .mp3 is passing through. It's just not creating a folder and then saving a file like the above .edu example.
What should I do?
I think you should do something like that -[Note: this i used for some other formats not mp3 but its works on my app for multiple format so i hope it will work for u too.]
InputStream in = this.getAssets().open("tmp.mp3"); //give path as per ur app
byte[] data = getByteData(in);
Make sure u have the folder already exists on path, if folder is not there it will not save content correctly.
byteArrayToFile(data , "testfolder/tmp.mp3"); //as per ur sdcard path, modify it.
Now the methods ::
1) getByteData from inputstream -
private byte[] getByteData(InputStream is)
{
byte[] buffer= new byte[1024]; /* or some other number */
int numRead;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try{
while((numRead = is.read(buffer)) > 0) {
bytes.write(buffer, 0, numRead);
}
return bytes.toByteArray();
}
catch(Exception e)
{ e.printStackTrace(); }
return new byte[0];
}
2) byteArrayToFile
public void byteArrayToFile(byte[] byteArray, String outFilePath){
FileOutputStream fos;
try {
fos = new FileOutputStream(outFilePath);
fos.write(byteArray);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have a png file in the raw folder. I get the inputStream using :
inputStream = getResources().openRawResource(R.raw.test);
I am trying to write this inputStream in a new file in an Android application. This is my code:
inputStream = getResources().openRawResource(R.raw.test);
File file = new File("/test.png");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024*1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
When I run the application, I get the following error in the logcat:
java.io.FileNotFoundException: /test.png: open failed: EROFS (Read-only file system)
Basically I want to create a File object so that I can send this to my server.
Thank you.
You will not have access to the file-system root, which is what you're attempting to access. For your purposes, you can write to internal files new File("test.png"), which places the file in the application-internal storage -- better yet, access it explicitly using getFilesDir().
For truly temporary files, you might want to look into getCacheDir() -- should you forget to delete those temporary files, the system will reclaim the space when it runs out of room.
Here's my solution:
inputStream = getResources().openRawResource(R.raw.earth);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
file.createNewFile();
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024*1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
I need to find a way how to create files from specific folder in Internal Storage of my device to a specific folder in External Storage.
Example :
I have 50 image files in data/data/app_package/files/documents/server/userId/storage/ in Internal Storage.
I want to copy all of the files in that directory to /sdcard/Documents/Server/UserId/Storage/
And the idea is that in some cases maybe I'll have to move files like 50MB and maybe more. Any suggestions how can I achieve this?
try this code
private void copyToFolder(String path) throws IOException {
File selectedImage = new File(path);
if (selectedImage.exists()) {
String wall = selectedImage.getName();
in = getContentResolver().openInputStream(selectedImageUri);
out = new FileOutputStream("/sdcard/wallpapers/" + wall);
copyFile( in , out); in .close(); in = null;
out.flush();
out.close();
out = null;
} else {
System.out.println("Does not exist");
}
}
private void copyFile(InputStream in , OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in .read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}