I've a functionality in my application in which I save a doc/img file path in my database. This file is lying in a folder (E.g. "/mnt/sdcard/MyApp/MyItem/test.png"). Now what i want to do is to copy this file to other folder (E.g. /mnt/sdcard/MyApp/MyItem/Today/test.png).
Right now I am using the code below but it's not working :
private void copyDirectory(File from, File to) throws IOException {
try {
int bytesum = 0;
int byteread = 0;
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
} catch (Exception e) {
}
}
and on button click am using the following code :
File sourceFile = new File(fileList.get(0).getAbsolutePath); //comes from dbs
File targetFile = new File(Environment.getExternalStorageDirectory(),"MyApp/MyItem/Today/");
copyDirectory(sourceFile,targetFile, currDateStr);
Any idea why it's not working?
This code is working fine for me.
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
And one more thing have you added in Manifest file *permission to write to external storage.*
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Yup got it working, I was not giving file name while copying the files, and didnt really look at error log, got it working now thanks. And yea the above code works just fine.
Related
I use this code but it fails at the file outputstream.
When i make a static void then getResources will fail.
public void copy (Context context) {
InputStream in = getResources().openRawResource(R.raw.high1);
FileOutputStream out = new FileOutputStream("/sdcard/pic1.jpg");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
To getResources() do not fail when changing it to static, modify the line:
InputStream in = getResources().openRawResource(R.raw.high1);
To:
InputStream in = context.getResources().openRawResource(R.raw.high1);
Additionally, quoting CommonsWare:
NEVER HARDCODE PATHS. Use getExternalFilesDir(), or Environment.getExternalStoragePublicDirectory(), or something like that to get a directory on external storage to use.
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 want to bundle an image with my application. I am planing to keep the image in the drawable or the raw folder. I wanted to know how to make a File object of this image?
Something like this:
File file = new File("fileurl");
Thank you.
Can you please try this one ?
try {
File mFile=new File("my file name");
InputStream inputStream = getResources().openRawResource(R.drawable.ic_launcher);
OutputStream out=new FileOutputStream(mFile);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
Hope this will help you.
If you put your image resource inside your Raw folder within your workspace, you can access it inside your class by using :
getResources.openRawResources(R.raw.resource_id)
EDIT :
the above code will return an inputStream, to convert it to file, try this one :
inputStream = getResources.openRawResources(R.raw.resource_id)`
// write the inputStream to a FileOutputStream
File file = new File("fileurl");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
I am trying to move file from /mnt/sdcard to /mnt/extsd
Currently file is stored in /mnt/sdcard/DCIM/camera after shooting a video
but now i want to move this file to /mnt/extsd
I am using following code
File fromFile=new File( "/mnt/sdcard/folderpath" ,"/video.mp4");
File toFile=new File("/mnt/extsd" ,fromFile.getName());
fromFile.renameTo(toFile);
I read that renameTo dosen't work for moving in different file systems
Please help me
try {
java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);
java.io.FileOutputStream fosto = new FileOutputStream(toFile);
byte bt[] = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c); //将内容写到新文件当中
}
fosfrom.close();
fosto.close();
} catch (Exception ex) {
Log.e("readfile", ex.getMessage());
}
}
give source file where exist ur file and target location where u want to store .
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
according to Android docs "Both paths must be on the same mount point" like it could be used for file renaming only in case of different paths. So if you want to move it you probably should copy it and then rename and then delete the source file. But in this case you are trying not only to move the file from one FS to another but also you are trying to use /mnt/extsd which might not be able at all. Follow this question about such paths.
I'm trying to copy an xml file from the res/xml folder to the device storage but I'm really struggling on how to do this.
I know that the starting point is to get an InputStream to read the xml file. This is achieved by using this:
InputStream is = getResources().openRawResource(R.xml.xmlfile);
Eventually the output stream will be:
file = new File("xmlfile.xml");
FileOutputStream fileOutputStream = new FileOutputStream(file);
But I'm really struggling on how to read and copy all the information from the initial xml file correctly and accurately.
So far, I've tried using various InputStream and OutputStream to read and write (DataInputStream, DataOutputStream, OutputStreamWriter, etc.) but I still didn't managed to get it correctly. There are some unknown characters (encoding issue?) in the produced xml file. Can anyone help me on this? Thanks!
From res/xml you can't you have to put all files in your assets folder then use below code
Resources r = getResources();
AssetManager assetManager = r.getAssets();
File f = new File(Environment.getExternalStorageDirectory(), "dummy.xml");
InputStream is = = assetManager.open("fileinAssestFolder.xml");
OutputStream os = new FileOutputStream(f, true);
final int buffer_size = 1024 * 1024;
try
{
byte[] bytes = new byte[buffer_size];
for (;;)
{
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
is.close();
os.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
I think you should use the raw folder instead. Have a look at http://developer.android.com/guide/topics/resources/providing-resources.html.
You can also use this code:
try {
InputStream input = getResources().openRawResource(R.raw.XZY);
OutputStream output = getApplicationContext().openFileOutput("xyz.mp3", Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
And when you need file use this code:
File k =getApplicationContext().getFileStreamPath("xyz.mp3");