How do I use this copy code [duplicate] - android

This question already has an answer here:
I need to be able to store sound files for my application on sdcard
(1 answer)
Closed 2 years ago.
I found this code which appears to be what I need in that it will copy byte for byte a file to the SDCard.
But how do I use it? say I have a text file called mytext.txt where do I put it in my application? and how would I reference it? I am using Eclipse
public static final void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied to " + f2.getAbsolutePath());
} catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch(IOException e){
System.out.println(e.getMessage());
}
}

I would make a FileUtilities class or somesuch. Have you looked at the examples here?
http://download.oracle.com/javase/tutorial/essential/io/copy.html
http://www.java2s.com/Code/Java/File-Input-Output/FileCopyinJava.htm
You don't want to blindly execute this code. It looks like it's meant for a java console app. System Printlines do not go anywhere that the user would see in an android application. I do not know what System.exit() does in an Android application, but you don't want to do this either. Depending on your application, you may want to add a toast notification that a copy fails. You want to at least log this.
Depending on the size of files you are copying, you may want to do this in a background thread as to not clog up your UI.

Well, at first glance that appears to be a sound method, except that you'd want to replace the System.out print statements with an android Log method... but besides that you could copy/paste that and include that method in a class.
To use it, however... you should have a look at the External Storage documentation.
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
You're going to need to use Android methods to get correct sdcard directories, etc...

You can add it as another method of your own Activity if your code is small, or you can create a utility class, let's suppose
class MyUtilities {
public static final void copyfile(String srFile, String dtFile) throws IOException, FileNotFoundException{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d("MyUtilities", "File copied to " + f2.getAbsolutePath());
}
}
and you will use it as:
TextEdit text1 = findViewById(R.id.text1);
TextEdit text2 = findViewById(R.id.text2);
String file1 = text1.getText();
String file2 = text2.getText();
if (text1 != null and text2 != null) {
try{
MyUtilities.copyfile (file1, file2);
} catch(FileNotFoundException ex){
Log.e("MyUtilities", ex.getMessage() + " in the specified directory.");
} catch(IOException e){
Log.e("MyUtilities", e.getMessage());
}
}
I added logs instead of the System.out and changed the Exception mechanism to better match android needs.

Related

Is There A Way To Store SharedPreferences to SDcard?

I've written an app that has several hard-coded settings such as fontSize or targetDirectory. I would like to be able to change those type of settings on an infrequent basis.
SharedPreferences seems to be one way to go about it but I want to share this application and settings, and my phone is not rooted.
My application is a personal tool, and does not have a UI. It opens, does it's job, and then closes. I could create the equivalent of a Windows .ini file and read/write to it, but that seems clunky. Having the SharePreferences file located on the sdcard where I can reach it, instead of device memory, where I can't, seems like that would work.
I do not want to backup these preferences, just be able to edit them, or copy them to a new device.
By default SharedPreferences files are stored in internal storage. You can make a backup of it to SD card programmatically.
File ff = new File("/data/data/"
+ MainActivity.this.getPackageName()
+ "/shared_prefs/pref file name.xml");
copyFile(ff.getPath().toString(), "your sdcard path/save file name.xml");
private void copyFile(String filepath, String storefilepath) {
try {
File f1 = new File(filepath);
File f2 = new File(storefilepath);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You may replace it back when first start and backup it when application closed.
References: here

Download(copy?) a file from my res/raw folder to the default Android download location?

I am making a soundboard for practice and I want to give the user the ability to download the sound (that I have included in the app in the res/raw folder) onClick of a menu item but I can only find information about downloading from an internet url, not something that I already included in the apk.
What is the best way to do this? I would like to give them the option to save to an SD card also if this is possible. A point towards the correct class to use in the documentation would be great! I've been googling to no avail.
Thanks!
Try something like this:
public void saveResourceToFile() {
InputStream in = null;
FileOutputStream fout = null;
try {
in = getResources().openRawResource(R.raw.test);
String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String filename = "myfile.mp3"
fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
I don't know about the raw but I did a similar thing in my app using the assets folder. My files are under the assets/backgrounds folder as you can probably guess from the code below.
You can modify this code and make it work for you (I know I will only have 4 files which is why I have i go from 0 to 4 but you can change this to whatever you want).
This code copies the file starting with prefix_ (like prefix_1.png, prefix_2.png, etc) to my cache directory but you can obviously change the extension, the filename or the path you would like to save the assets to.
public static void copyAssets(final Context context, final String prefix) {
for (Integer i = 0; i < 4; i++) {
String filename = prefix + "_" + i.toString() + ".png";
File f = new File(context.getCacheDir() + "/" + filename);
if (f.exists()) {
f.delete();
}
if (!f.exists())
try {
InputStream is = context.getAssets().open("backgrounds/" + filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) {
Log.e("Exception occurred while trying to load file from assets.", e.getMessage());
}
}
}

mp3 not saving to sd correctly; how to save mp3 to sd card?

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

Android: Correctly downloading/saving an email attachement

I have an interesting problem: My application is designed to send and open up a zip full of files, and the zip has a special extension (easier for the user). I can zip up the files I need to attach in an e-mail, and I can send them.
When I use the g-mail "view" button and select my app to open the file, it doesn't unzip them correctly. However, if I use the gmail "download" button, and then open the file through a file explorer, the file unzips correctly.
This is the code I use to download the attachment:
// get attachment
try {
attachment = getContentResolver().openInputStream(
getIntent().getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Save it
try {
File root = Environment.getExternalStorageDirectory();
path = root.getPath() + "/PSattachment.psz";
savedFile = new File(path);
FileOutputStream fos = new FileOutputStream(savedFile, false);
BufferedOutputStream os = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int byteRead = 0;
while ((byteRead = attachment.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Am I doing something wrong? Thanks in advance. (Also, the process of unzipping is the same in both cases [file explorer and view from email], so I'm pretty sure it's something in here. Also, the file DOES download, and is the right size. It just won't unzip).
I found the answer!!! Took a while, but at least it works now:
try {
InputStream attachment = getContentResolver()
.openInputStream(getIntent().getData());
savedFile = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"temp" + System.currentTimeMillis() + ".psz");
FileOutputStream f = new FileOutputStream(savedFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = attachment.read(buffer)) > 0) {
f.write(buffer);
}
f.close();
} catch (Exception e) {
}
I just used this code to download the attachment and now everything works perfectly =D
Check this out please:
http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically)
A guide to unzip files in android, hope it helps solve your problem

Creating files in sub directories in android

Is it possible to create files in subdirectories created under "/data/data/packagename/files/" directory using openFileOutput method in android?
ie there is a sub-directory by name "text" inside the "/data/data/packagename/files/" directory.
I want to use the openFileOutput (String name, int mode) method to write a file eg:sample.txt into this directory....
Is it possible to use openFileOutput method to do it....
Can any one help me on this....
Not with openFileOutput, but you can use the regular java.io.File methods.
java.io.File.mkdir()
to create a directory, and for example for copying (can adjust for creating) a file from sdcard to some data subdir:
public static final void copyfile(String srFile, String dtFile){
Log.d(MyApp.APP,"copyfile " + srFile + " -> " + dtFile );
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d(MyApp.APP,"File copied to " + f2.getAbsolutePath());
} catch(FileNotFoundException ex){
Log.e(MyApp.APP,"Error.",ex);
} catch(IOException e){
Log.e(MyApp.APP,"Error.",e);
}
}

Categories

Resources