I have a file located at /res/introduced.xml. I know that I can access it in two ways:
1) the R.introduced resource
2) some absolute/relative URI
I'm trying to create a File object in order to pass it to a particular class. How do I do that?
This is what I ended up doing:
try{
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp 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);
}
}
some absolute/relative URI
Very few things in Android support that.
I'm trying to create a File object in order to pass it to a particular class. How do I do that?
You don't. A resource does not exist as a file on the filesystem of the Android device. Modify the class to not require a file, but instead take the resource ID, or an XmlResourceParser.
Related
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 text file in the assets folder that I need to turn into a File object (not into InputStream). When I tried this, I got "no such file" exception:
String path = "file:///android_asset/datafile.txt";
URL url = new URL(path);
File file = new File(url.toURI()); // Get exception here
Can I modify this to get it to work?
By the way, I sort of tried to "code by example" looking at the following piece of code elsewhere in my project that references an HTML file in the assets folder
public static Dialog doDialog(final Context context) {
WebView wv = new WebView(context);
wv.loadUrl("file:///android_asset/help/index.html");
I do admit that I don't fully understand the above mechanism so it's possible that what I am trying to do can't work.
Thx!
You cannot get a File object directly from an asset, because the asset is not stored as a file. You will need to copy the asset to a file, then get a File object on your copy.
You cannot get a File object directly from an asset.
First, get an inputStream from your asset using for example AssetManager#open
Then copy the inputStream :
public static void writeBytesToFile(InputStream is, File file) throws IOException{
FileOutputStream fos = null;
try {
byte[] data = new byte[2048];
int nbread = 0;
fos = new FileOutputStream(file);
while((nbread=is.read(data))>-1){
fos.write(data,0,nbread);
}
}
catch (Exception ex) {
logger.error("Exception",ex);
}
finally{
if (fos!=null){
fos.close();
}
}
}
Contrary to what others say, you can obtain a File object from an asset as follows:
File myAsset = new File("android.resource://com.mycompany.app/assets/my-asset.txt");
This function missing in code. #wadali
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);
}
}
Source: https://stackoverflow.com/a/4530294/4933464
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);
}
}
Official facebook App has a bug, when you try to share an image with share intent, the image gets deleted from the sdcard. This is the way you have to pass the image to facebook app using the uri of the image:
File myFile= new File(Environment.getExternalStorageDirectory(), "car.jpg");
Uri uri = Uri.fromFile(myFile);
i.putExtra(Intent.EXTRA_STREAM, uri);
Then, suppose that if i create a copy from the original myFile object, and i pass the uri of the copy to facebook app, then, my original image will not be deleted.
I tried with this code, but it doesn't work, the original image file is still getting deleted:
File myFile= new File(Environment.getExternalStorageDirectory(), "car.jpg");
File auxFile=myFile.getAbsoluteFile();
Uri uri = Uri.fromFile(auxFile);
Can someone tell me how to do a exact copy of a file that doesn't redirect to the original File?
Please check: Android file copy
The file is copied byte by byte so no reference to the old file is maintained.
Here, this should be able to create a copy of your file:
private void CopyFile() {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(<file path>);
out = new FileOutputStream(<output path>);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
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);
}
}
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.