File writing in external storage device is not working - android

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

Related

Android unzip zip file from internal storage

I am downloading zip file from server to internal storage. And after downloading I want to unzip that file in internal storage itself. My file is downloaded to internal storage and I can see that but while unzip I am not able to read it. Below is my unzipfile() method. Can anyone tell where I am going wrong?
public void unzipfile()
{
try {
Log.d("unzipiing","unzipping");
ContextWrapper cw = new ContextWrapper(context);
String name_="foldername"; //Folder name in device android/data/
File directory = cw.getDir(name_, Context.MODE_PRIVATE);
File mypath=new File(directory,"dwnld");
FileOutputStream fout = new FileOutputStream(mypath);
File yourFile = new File(directory,"dwnld.zip");
Log.d("unzipiing","filepath -" + yourFile.getPath());
FileInputStream fin = new FileInputStream(yourFile.getPath());
ZipInputStream zin = new ZipInputStream(fin);
Log.d("unzipiing","zin size -" + zin.available());
// zin.available() give -1 in console log
BufferedInputStream in = new BufferedInputStream(zin);
BufferedOutputStream out = new BufferedOutputStream(fout);
byte b[] = new byte[zin.available()];
int n;
Log.d("unzip","n - " + in.read(b,0,1024));
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
Log.d("unzip byte"," - " + n);
}
out.flush();
out.close();
in.close();
fin.close();
zin.close();
}
catch (Exception e){
}
}
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
use this method for unzip
public void unzip(String _zipFile, String _targetLocation) {
//create target location folder if not exist
dirChecker(_targetLocatioan);
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
check the path
public void dirChecker(String filepath)
{
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
}

prevent storing a video file twice in internal storage in android

how to prevent storing same file selected in galary twice in internal storage in android .I tried with below code it copies same video many times in a folder in the internal storage .
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
new SaveVideoInFolder().execute(uri);
try {
InputStream is = getContentResolver().openInputStream(uri);
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, "video_choosing");
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
file = new File(app_directory, filename);
Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show();
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Log.e("TAG", "File Not Found", e);
} catch (IOException e) {
Log.e("TAG", "IOException", e);
}
}
// Create the storage directory if it does not exist
if (!file.exists()) {
if (!file.mkdirs()) {
/* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");*/
return null;
}
only you have check that your file is exist bt if condition and make directory if it is not..
File file = new File(app_directory, filename);
if(file.exists()){
...
}
else {
...
}

copy a rar file from assets folder to external card

I am trying to copy two files from assets folder to external storage, one is a text based and another one is a rar file(60 kb). But when i open the rar file in file manager, it says "wrong header". The size of the rar file which i get is 16kb.
private void copyAsset() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(SKETCH_FILE);
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Ardumation");
if (!dir.exists()) {
//System.out.println("creating directory: " + directoryName);
dir.mkdir();
}
//File outFile = new File(getExternalFilesDir(null), SKETCH_FILE);
File sketchFile = new File(dir, SKETCH_FILE);
File libraryFile = new File(dir, LIBRARY_FILE);
if (!sketchFile.exists()){
out = new FileOutputStream(sketchFile);
copyFile(in, out);
}
if (!libraryFile.exists()){
out = new FileOutputStream(libraryFile);
copyFile(in, out);
}
} catch(IOException e) {
Log.e(TAG, "Failed to copy asset file: ", e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
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);
}
}
Now what is wrong..?

Copying file from subfolder in asset folder

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/

How to save a non txt file in data/files folder in android

A way to save a non text file to /data/files folder.
If file resource is from assets folder.
this should do it.
private void writeToSDCard() {
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
InputStream from = myContext.getResources().openRawResource(rID);
File dir = new java.io.File (root, "pdf");
dir.mkdir();
File writeTo = new File(root, "pdf/" + attachmentName);
FileOutputStream to = new FileOutputStream(writeTo);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
to.close();
from.close();
} else {
Log.d(TAG, "Unable to access SD card.");
}
} catch (Exception e) {
Log.d(TAG, "writeToSDCard: " + e.getMessage());
}
}
}

Categories

Resources