In the emulator I'm trying to write to the file:
/mnt/sdcard/Android/data/com.Me.MyApp/files/myFile.txt
I have set external write permissions in the Manifest, but I keep receiving a file not found exception. The emulator is configured to have an sd-card.
Why might that be?
InputStream is = c.getResources().openRawResource(R.raw.my_raw_file);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try
{
while (zis.getNextEntry() != null)
{
File destFile = new File(destinationPath);
// EXCEPTION THROWN NEXT LINE!
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[BUF_SIZE];
int count;
while ((count = zis.read(buffer)) != -1)
{
os.write(buffer, 0, count);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
zis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Try below code
String path = "/mnt/sdcard/Android/data/com.Me.MyApp/files";
File mFile = new File(path);
mFile.mkdirs();
Nammari's answer plus:
Android Tutorial: Creating and Using an SD Card in the Emulator
http://www.streamhead.com/android-tutorial-sd-card/
Related
Am trying to copy a file from a named subfolder in asset folder but am getting a "not found error" when trying to use the file. Apparently it seems am not copying the file right.
Here is what I have done maybe someone can spot my error
Method call:
copyfile("/lollipop/proxy.sh");
Method:
public void copyfile(String file) {
String of = file;
File f = new File(of);
String basedir = getBaseContext().getFilesDir().getAbsolutePath();
if (!f.exists()) {
try {
InputStream in =getAssets().open(file);
FileOutputStream out =getBaseContext().openFileOutput(of, MODE_PRIVATE);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
Runtime.getRuntime().exec("chmod 700 " + basedir + "/" + of);
} catch (IOException e) {
Log.e(TAG, "Error reading I/0 stream", e);
}
}
}
Trying to use the proxy.sh fails as the file seems it's never copied but when I remove the " lollipop " directory it works fine. What seems wrong? Tnx
openFileOutput() does not accept subdirectories. Since of points to /lollipop/proxy.sh, you are trying to create a subdirectory.
Those having issues accessing sub directories in asset folder since explanation to this isn't explicitly answered this is how I achieved it.
AssetManager assetManager = getAssets();
String[] files = null;
try {
if (Build.VERSION.SDK_INT >= 21)
files = assetManager.list("api-16");
else
files = assetManager.list("");
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
if (files != null) {
for (String file : files) {
InputStream in = null;
OutputStream out = null;
try {
if (Build.VERSION.SDK_INT >= 21)
in = assetManager.open("api-16/" + file);
else
in = assetManager.open(file);
out = new FileOutputStream("/data/data/yourpackagename/" + file);
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);
}
}
method call
Files are now accessible from
/data/data/yourpackagename/
so call the files from there. Using
getFilesDir()
won't work as it gets from
/data/data/yourpackagename/files/
I would like to copy an existing video file to another video file.
I trying to do it like this:
byte c;
try {
FileOutputStream newFile = new FileOutputStream (VIDEO_PATH_TMP);
FileInputStream oldFile = new FileInputStream (VIDEO_PATH);
while ((c = (byte) oldFile.read()) != -1) {
newFile.write(c);
}
newFile.close();
oldFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it doesn't work. The output file was created, but i can't see the video.
How can i implement this?
Thanks!
Ok, I found the answer and this is the code:
try {
FileOutputStream newFile = new FileOutputStream (VIDEO_PATH_TMP);
FileInputStream oldFile = new FileInputStream (VIDEO_PATH);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = oldFile.read(buf)) > 0) {
newFile.write(buf, 0, len);
}
newFile.close();
oldFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I just added the Buffer array and it solved the problem :)
I think you should call flush before close:
newFile.flush();
newFile.close();
I am creating an app that needs to read data from a file. I was initially reading it from the assets folder using a BufferedReader and an InputStreamReader but I was running into memory issues (see Android: File Reading - OutOfMemory Issue). One suggestion was to copy the data from the assets folder to the internal storage (not the SD card) and then access it via RandomAccessFile. So I looked up how to copy files from the assets to internal storage and I found 2 sources:
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/RpXiMYV48Ww
http://developergoodies.blogspot.com/2012/11/copy-android-asset-to-internal-storage.html
I decided to use the code from the second one and modified it for my file. So it looks like this:
public void copyFile() {
//Open your file in assets
Context context = getApplicationContext();
String destinationFile = context.getFilesDir().getPath() + File.separator + "text.txt";
if (!new File(destinationFile).exists()) {
try {
copyFromAssetsToStorage(context, "text.txt", destinationFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int length = Input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
}
private void copyFromAssetsToStorage(Context context, String sourceFile, String destinationFile) throws IOException {
InputStream inputStream = context.getAssets().open(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
copyStream(inputStream , outputStream );
outputStream.flush();
outputStream.close();
inputStream.close();
}
I am assuming that this copies the file into the app's data directory. I have not been able to test it because I would like to be able to access the file using RandomAccessFile. However, I have never done either one of these two (copying the file from assets and RandomAccessFile) so I am stuck. The work on this app has come to a standstill because this is the only thing that is preventing me from completing it.
Can anyone provide me with corrections, suggestions, and correct implementations of how to access the data using RandomAccessFile? (The data is a list of strings 4-15 characters in length on each line.)
EDIT*
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = context.getAssets().open(filename);
fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return cacheFile;
}
1- Copy the file from assets to the cache directory
This code just for illustration, you have to do appropriate exception handling and close resources
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = context.getAssets().open(filename);
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
fileOutputStream.close();
inputStream.close();
return cacheFile;
}
2- Open the file using RandomAccessFile
File cacheFile = createCacheFile(context, "text.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");
// Process the file
randomAccessFile.close();
On a side note, you should follow Java naming conventions, e.g. your method and variable name should start with small letter such as copyFromAssetsToStorage and destinationFile
Edit:
You should make a separate try/catch for each close() operation, so if one fails the other still get executed and check that they are not null
finally {
try {
if(fileOutputStream!=null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
I have been trying to export my database file into the external memory of my android phone by using
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";
//Get a reference to the database
File dbFile = this.getDatabasePath(DB_NAME);
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
It managed to create a directory name "myappsbackup" but my database couldnt be copied over. it is always size 0 and my tables are missing. Is there something wrong with my method of copying?
Here is the code I use to write or backup my SQLite db to the sdcard.
try {
db.open();
File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}