Android Copy and Rename from anywhere - android

Trying to use the following code to copy a file from one directory to another and rename
String Path3= "/storage/extSDCard/DCIM/Camera/fred.jpg";
File to = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Barr.jpg");
File oldFile = new File (Path3);
oldFile.renameTo(to);
It doesn't appear to copy the file. in this case the path Path3 is on the SDCard but I also need it to copy from one directory to another on the device as well
Basically I'm using the gallery picker to pick an image from somewhere I convert the uri to a path I then need to copy the file from where it is stored to the pictures directory and rename it
Any idea where I'm going wrong?

I solved it from A variety of sources was going about it in the wrong way. This Code Works:
File sourceLocation = new File (Path2);
File targetLocation = new File (Path3 + "/" + imageFileName);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
int actionChoice = 2;
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
else{
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

Related

How to create a shared folder usable by my android app?

I've got a question that probably borders on opinion, but I've not any related questions or documentation that answers, so I feel like it's a fair one to ask.
I'm trying to build an android app which modifies music files, and what I'd like to do is have a shared folder so that the files and the results can be accessible and shared. I'd like it if it was among the other folders like Music, Downloads, Movies, etc, or even under Music since it's music related. However this seems like it's a security no no in Android, as after I've made something and put it in there I have to use an intent to access it again, where as I'd rather just be able to open the files and not have a permissions based fiasco. Maybe some type of symbolic link like in Linux that pointed to my apps internal folder could be used, but of this I'm still uncertain.
In any case, is there a way I should go about this? If so, are there some resources I could be pointed to?
Thank you in advance to anyone who takes this up!
Edit for CommonsWare:
I used the following to create the folder:
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), APP_NAME);
And this to copy files from elsewhere to there:
public void copyFileToHomeDirectory(Uri uri)
{
try
{
ContentResolver contentResolver = getApplicationContext().getContentResolver();
String fileName = queryName(contentResolver, uri);
//Get file extension
String fileType = fileName.substring(fileName.length() - 4, fileName.length());
if(fileType.equalsIgnoreCase(MP3_EXTENSION))
{
String path = Environment.getExternalStorageDirectory() + APP_FOLDER;
InputStream in = contentResolver.openInputStream(uri);
File outputFile = new File(path + File.separator + fileName);
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
//First we crack open the file to copy it's contents:
byte[] buffer = new byte[KB_SIZE];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file (You have now copied the file)
out.flush();
out.close();
out = null;
}
}
catch(FileNotFoundException fnfe)
{
Log.e(TAG, "FileNotFoundException");
Log.e(TAG, Log.getStackTraceString(fnfe));
}
catch(IOException ioe)
{
Log.e(TAG, "IOException");
Log.e(TAG, Log.getStackTraceString(ioe));
}
catch(Exception e)
{
Log.e(TAG, "General Exception");
Log.e(TAG, Log.getStackTraceString(e));
}
}
I've tried other methods that I've overwritten in the process, but accessing the files to be used again I need something like this:
public void openDirectory(View view)
{
// Choose a directory using the system's file picker.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// Provide read access to files and sub-directories in the user-selected
// directory.
//intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
//intent.addCategory(Intent.CATEGORY_OPENABLE);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when it loads.
//intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriToLoad);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*"); //use image/* for photos, etc.
//The result of this code will be calling the onActivityResult function below
startActivityForResult(intent, REQUEST_MUSIC_DIR);
}
Edit2:
I've reorganized the folders to what I think I should be doing so that I can work with the files freely, however, even in my internal cache storage (getCacheDir() + folder_name) either isn't letting me create the files (outputFile.createNewFile doesn't throw an error) or it isn't letting me open them when I go to get a directory listing.
Here's my code for creating the file:
String path = getCacheDir() + MY_SUB_FOLDER;
//uri is obtained through ACTION_OPEN_DOCUMENT intent
InputStream in = contentResolver.openInputStream(uri);
File outputFile = new File(path + "/" + fileName);
outputFile.createNewFile();
Log.i(TAG, "The new file's directory/path is: " + outputFile.getAbsolutePath());
//NOTE: This is returning /data/user/0/com.example.myapplication/cache/MY_SUB_FOLDER/file_name.mp3
OutputStream out = new FileOutputStream(outputFile);
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;
This is my code for attempting to open and read these newly created files
File directory = new File(getCacheDir(), MY_SUB_FOLDER);
Log.i(TAG, "This is the directory we're trying to get the files from: " + directory.getAbsolutePath());
//NOTE: This returns /data/user/0/com.example.myapplication/cache/MY_SUB_FOLDER
File[] files = directory.listFiles();
if(files != null)
{
for(int i = 0; i < files.length; i++)
{
Log.d(TAG, "Files found: " + files[i].getAbsolutePath());
}
}
The files variable isn't null but it's length is 0 and no files are found.
Edit3:
I am catching the exceptions and logging any stack traces, which currently returns nothing.
catch(FileNotFoundException fnfe)
{
Log.i(TAG, "FileNotFoundException");
Log.i(TAG, Log.getStackTraceString(fnfe));
}
catch(IOException ioe)
{
Log.i(TAG, "IOException");
Log.i(TAG, Log.getStackTraceString(ioe));
}
catch(Exception e)
{
Log.i(TAG, "General Exception");
Log.i(TAG, Log.getStackTraceString(e));
}

Files.list returns null for android data/data device is rooted

I'm trying to generate a list of all the files in a particular directory in /data/data/ e.g. /data/data/com.package.ect so that I can zip them. My device is rooted and I've granted Super User to my app. When pass the path to the directory it gets past the if statement, so it recognises that what I'm trying to access is a directory, yet File.list() returns null. I'm assuming I'm still lacking some sort of permission.
/**
* Traverse a directory and get all files,
* and add the file into fileList
* #param node file or directory
*/
public void generateFileList(File node) {
//add file only
if (node.isFile()) {
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
generateFileList(new File(node, filename));
}
}
}
*EDIT: As requested where generateFileList is called
public void zipDirectory(String outputPath){
byte[] buffer = new byte[1024];
try{
checkStorageDirExists(SDCARD, STORAGE_LOCATION);
generateFileList(new File(path));
FileOutputStream fos = new FileOutputStream(SDCARD + STORAGE_LOCATION + outputPath);
ZipOutputStream zos = new ZipOutputStream(fos);
setZipFileName(path);
Log.i(TAG, "Output to Zip : " + outputPath);
for(String file : this.fileList){
System.out.println("File Added : " + file);
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in =
new FileInputStream(path + "/" + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
zos.close();
Log.i(TAG, "Zip of " + getZipFileName() +" Completed");
}catch(IOException ex){
ex.printStackTrace();
}

changing byte when copy file not working

changing byte when copy file form one location to another not working whats wrong in my code please help me if i remove string s1; then its work perfect just duplicate original file when i alter bytes using s1 string its not work
samplet.text file contain numbers
3434214280
3044559080
3154356865
3312430124
3334491537
package com.example.copyfilefromdirectorytoanother;
ublic class MainActivity extends Activity {
private static final String TAG = "MainActivity.java";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your sd card
String sdCard = Environment.getExternalStorageDirectory().toString();
// the file to be moved or copied
File sourceLocation = new File (sdCard + "/sample.txt");
// make sure your target location folder exists!
File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");
// just to take note of the location sources
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else{
// make sure the target file exists
if(sourceLocation.exists()){
InputStream in = new
FileInputStream(sourceLocation);
OutputStream out = new
FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
String s1;
// byte[] theByteArray ;
byte[] buf = new byte[1024];
byte[] theByteArray = new byte[1024];
int len;
int n =1;
while ((len = in.read(buf)) > 0) {
s1= "BEGIN:VCARD \n VERSION:2.1 \n N:;UNKNOWN "+n+";;; \n FN:UNKNOWN "+n+"
\n TEL;CELL;PREF:+92"+buf+" \n END:VCARD ";
theByteArray=s1.getBytes();
out.write(theByteArray, 0, len);
n=n+1;
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file
missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Well, you're reading in len bytes, appending data to it, then writing out len bytes. That's wrong, you need to do out.write(theByteArray, 0, theByteArray.length); I can see other possible problems there too, but your file may be small enough to avoid them.

Android unzip open failed: ENOENT (No such file or directory)

I am using the following code to unzip a set of files (containing folders as well):
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
// zapis do souboru
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
// cteni zipu a zapis
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
The code fails on FileOutputStream fout = new FileOutputStream(path + filename) with the error:
java.io.FileNotFoundException: /storage/emulated/0/BASEFOLDER/FOLDER1/FILE.png
BASEFOLDER already exists, that is where I am trying to unzip the folder to. If I manually (or programmatically) create FOLDER1, the code runs fine and successfully unzips. I believe it is crashing because the very first file (ze) is named FOLDER1/FILE.png and FOLDER1 hasn't been created yet. How do I get around this? I know other people have used this code, I find it unlikely that it randomly doesn't work for me...
Have you got this in your AndroidManifest.xml file?
Add Write to external Storage permission
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I had the same problem. After several investigation I found that. put following single line in your code:
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
zis.closeEntry(); // <<<<<< ADD THIS LINE
continue;
}
Sometime the extract files has been extracted before its parent directory is created, for example:
File A inside directory B. But B directory is not created, index of files listing below cause the issue:
dir_b/file_a.txt
dir_b/
dir_b/file_c.txt
So, to sure directory created before file extracting, you need to create parent directories first, for example:
val targetFile = File(tempOutputDir, zipEntry.name)
if (zipEntry.isDirectory) {
targetFile.mkdirs()
} else {
try {
try {
targetFile.parentFile?.mkdirs() // <-- ADD THIS LINE
} catch (exception: Exception) {
Log.e("ExampleApp", exception.localizedMessage, exception)
}
val bufferOutputStream = BufferedOutputStream(
FileOutputStream(targetFile)
)
val buffer = ByteArray(1024)
var read = zipInputStream.read(buffer)
while (read != -1) {
bufferOutputStream.write(buffer, 0, read)
read = zipInputStream.read(buffer)
}
bufferOutputStream.close()
} catch (exception: Exception) {
Log.e("ExampleApp", exception.localizedMessage, exception)
}
}

Android: How to create a directory on the SD Card and copy files from /res/raw to it?

I am trying to create a folder and several subdirectory within it on the SD Card... I then want to transfer files that I have stored in /res/raw to that folder... I addition, I want this to only happen once, the first time the program is ever run. I realize that this is ridiculously open-ended, and that I am asking a lot... but any help would be greatly appreciated.
This will copy all files in the "clipart" subfolder of the .apk assets folder to the "clipart" subfolder of your app's folder on the SD card:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String basepath = extStorageDirectory + "/name of your app folder on the SD card";
//...
// in onCreate
File clipartdir = new File(basepath + "/clipart/");
if (!clipartdir.exists()) {
clipartdir.mkdirs();
copyClipart();
}
private void copyClipart() {
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(int i=0; i<files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + files[i]);
out = new FileOutputStream(basepath + "/clipart/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}
}
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 experienced a similar problem when using mkdirs(), however because running the command:
mkdir one/two
fails on Linux, then the method http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdirs() subsequently fails too. I guess this means there is no way to use mkdirs on Android? My (probably rather hacky) work-around was to create each necessary directory separately:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
new File(extStorageDirectory + "/one/").mkdirs();
new File(extStorageDirectory + "/one/two/).mkdirs();

Categories

Resources