How to read and write files to removable sd card in Android?
I want to store Android Id in Text file. The text file should be created on external sdcard.
Code:
PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
File myFile = new File(s + "/MyDoople.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(TxtS.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Text Updated",Toast.LENGTH_SHORT).show();
The Second is
File sdCard = new File("file:///mnt/external_sd/");
File myFile = new File(sdCard, "test.txt");
FileWriter writer = new FileWriter(myFile);
writer.append(TESTSTRING);
writer.flush();
writer.close();
Try the below. Use Environment.getExternalStorageDirectory() to get the path
File dir =new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder");
if(!dir.exists())
{
dir.mkdirs();
}
String filename= "MyDoople.txt";
try
{
File f = new File(dir+File.separator+filename);
FileOutputStream fOut = new FileOutputStream(f);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append("Mytest");
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Text Updated",
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
To update:
try
{
FileWriter fileWritter = new FileWriter(f,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("Mydata");
bufferWritter.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Result on my device when i opened with a text file viewer.
Edit:
The below is hackish and not the recommended way.
In my device (Samsung Galaxy s3) my internal phone memory is named sdCard0 and my external
extSdcard. This Environment.getExternalStorageDirectory() will give path of internl memory. In such cases you can use the below to get path of external memory.
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
private static String getExternalStoragePath(Context mContext) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (removable == true) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
and enter this code.
It return path of SD Card path if SD card is available
and then you can use that path .
String sdCardPath = getExternalStoragePath(context);
File Path1 = new File(sdCardPath + "NewFolder");
if (!Path1.exists()) {
Path1.mkdir();
}
File file = new File(Path1, "test.txt");
Maybe you forget these permissions.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
package com.example.writeinsdcard;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "Sdcard";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Howdy do to you.");
pw.println("Here is a second line.");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to:\n"+file);
}
/** Method to read in a text file placed in the res/raw directory of the application. The
method reads in all lines of the file sequentially. */
private void readRaw(){
tv.append("\n\nData read from res/raw/textfile.txt:\n");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer size
// More efficient (less readable) implementation of above is the composite expression
/*BufferedReader br = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.textfile)), 8192);*/
try {
String test;
while (true){
test = br.readLine();
// readLine() returns null if no more lines in the file
if(test == null) break;
tv.append("\n"+" "+test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.writesdcard"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<!--permission to write external storage -->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.writesdcard.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My question is solved.
I directly use the path "/mnt/external_sd/.. Path of File.".
But it was only work with my Device
Related
Im trying to backup my sqlite database to my sdcard and I'm trying to follow This way but I cant find the database in my sdcard. What did I do wrong?
public void exportDatabse(String DBOperations) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//com.example.hp.semakoperasimampatansrc//databases//attendant_info.db";
String backupDBPath = "attendant_info_backup.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
How I call the method:
db.exportDatabse("attendant_info.db");
I've also have added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to my manifest
You can do same in following way and this can be used to copy not only database, but files and shared pref also (if any). Create a class called DeveloperOption and use its method copyAppDataToLocal to do same.
Runtime permission is required if target sdk is 23 or above
//package declaration
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class DeveloperOption {
public static final String BASE_PATH = Environment.getExternalStoragePublicDirectory
("App_BackUp").getAbsolutePath();
public static final String SEPARATOR = "/";
private static boolean operationStatus = true;
private static String dataDirectory = null;
private static String appName = "APP_NAME";
public static boolean copyAppDataToLocal(Activity callingActivity, String appName) {
dataDirectory = callingActivity.getApplicationInfo().dataDir;
DeveloperOption.appName = appName;
String TAG = "Developer_Option";
try {
if(dataDirectory != null) {
copyAppData(new File(dataDirectory, "shared_prefs"),"shared_prefs");
copyAppData(new File(dataDirectory, "files"),"files");
copyAppData(new File(dataDirectory, "databases"),"databases");
} else {
Log.e(TAG, "!!!!!Unable to get data directory for ACTIVITY-->" + callingActivity
.toString());
}
} catch (Exception ex) {
Log.e(TAG, "!!!!###Exception Occurred while copying DATA--->"+ex.getMessage(),ex.fillInStackTrace());
operationStatus = false;
}
return operationStatus;
}
private static void copyFileToStorage(String directoryName, String inFile, String fileName, boolean
isDirectory, String subdirectoryName) {
try {
FileInputStream myInput = new FileInputStream(inFile);
File out_dir;
if(!isDirectory) {
out_dir = new File(BASE_PATH+ SEPARATOR + appName +
SEPARATOR + directoryName);
} else {
out_dir = new File(BASE_PATH + SEPARATOR + appName +
SEPARATOR + directoryName + SEPARATOR + subdirectoryName);
}
if(!out_dir.exists()) {
operationStatus = out_dir.mkdirs();
}
String outFileName = out_dir + "/" + fileName;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer1 = new byte[1024];
int length;
while ((length = myInput.read(buffer1)) > 0) {
myOutput.write(buffer1, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copyAppData(File fileTypeToBeCopied, String outDirectoryName){
if(fileTypeToBeCopied.exists() && fileTypeToBeCopied.isDirectory()) {
File[] files = fileTypeToBeCopied.listFiles();
for (File file : files) {
if(file.isFile()) {
copyFileToStorage(outDirectoryName, file.getAbsolutePath(), file.getName(), false, "");
} else {
String folderName = file.getName();
File databaseDirsNew = new File(dataDirectory, outDirectoryName+"/" + folderName);
if(databaseDirsNew.exists() && databaseDirsNew.isDirectory()) {
File[] filesDB = databaseDirsNew.listFiles();
for (File file1 : filesDB) {
if(file1.isFile()) {
copyFileToStorage(outDirectoryName, file1.getAbsolutePath(), file1.getName(),
true, folderName);
}
}
}
}
}
}
}
}
Try adding runtime permission request for Android 6.0 (API Level 23) and above, from official docs
Code for getting WRITE_EXTERNAL_STORAGE permission
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 && !checkIfAlreadyhavePermission()) {
requestForSpecificPermission();
}
private boolean checkIfAlreadyhavePermission() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
return false;
}
return true;
}
Ask for permission else like this
private void requestForSpecificPermission() {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}
try out this.
public void exportDatabse(String DBOperations){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "//data//com.example.hp.semakoperasimampatansrc//databases//attendant_info.db";
String backupDBPath = DBOperations;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
What's wrong with the code? I added the permission already. Logcat isn't printing the message it's supposed to show.
I'm guessing I have to use a filestream?
public class Run {
int abc = 2;
int[] myIntArray = {1,2,3};
String texts = "abcabac";
//Person p = new Person();
Paragraph p = new Paragraph(abc, texts, myIntArray);
Serializer serializer = new Persister();
File file = new File("paragraphs.xml");
private final static String TAG = Run.class.getCanonicalName();
String a = "writeing something nothing";
// Now write the level out to a file
Serializer serial = new Persister();
//File sdDir = Environment.getExternalStorageDirectory(); should use this??
//File sdcardFile = new File("/sdcard/paragraphs.xml");
File sdcardFile = new File(Environment.getExternalStorageDirectory().getPath());
{
try {
serial.write(p, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
I have samsung galaxy s3 with android 4.1.2. My internal phone memory is named sdcard0 and my external card extSdCard.
Environment.getExternalStorageDirectory()
So the above returns the path of sdcard0 which is internal phone memory
In such cases to get the actual path you can use the below
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
Once you get the path you can use the below.
Try the below
String filename = "filename.xml";
File file = new File(Environment.getExternalStorageDirectory(), filename);
//Instead of Environment.getExternalStorageDirectory() you can use internalpath or externalpath from the above code.
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
//to get sdcard path
String sdcardpath = Environment.getExternalStorageDirectory().getPath();
//to write a file in sd card
File file = new File("/sdcard/FileName.txt");
if (!file.exists()) {
file.mkdirs();
}
Permission to add in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
you have to do
filename is test.xml,text.jpg or test.txt
File sdcardFile = new File(Environment.getExternalStorageDirectory()+"/"+filename);
cehck this link.
for more detail about External Storage
I put a zip file in the android assets. How do i extract the file in the android internal storage? I know how to get the file, but i don't know how to extract it. This is my code..
Util zip ;
zip = new Util();
zip.copyFileFromAsset(this, "myfile.zip", getExternalStorage()+
"/android/data/edu.binus.profile/");
Thanks for helping :D
This piece of code will help you....Just pass the zipfile location and the location where you want the extracted files to be saved to this class while making an object...and call unzip method...
public class Decompress {
private String zip;
private String loc;
public Decompress(String zipFile, String location) {
zip = zipFile;
loc = location;
dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(zip);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(loc + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
Based on Sreedev R solution,
I added the option to read the file from assets and use buffer:
package com.pixoneye.api.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.content.Context;
import android.util.Log;
public class Decompress {
private static final int BUFFER_SIZE = 1024 * 10;
private static final String TAG = "Decompress";
public static void unzipFromAssets(Context context, String zipFile, String destination) {
try {
if (destination == null || destination.length() == 0)
destination = context.getFilesDir().getAbsolutePath();
InputStream stream = context.getAssets().open(zipFile);
unzip(stream, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void unzip(String zipFile, String location) {
try {
FileInputStream fin = new FileInputStream(zipFile);
unzip(fin, location);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void unzip(InputStream stream, String destination) {
dirChecker(destination, "");
byte[] buffer = new byte[BUFFER_SIZE];
try {
ZipInputStream zin = new ZipInputStream(stream);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v(TAG, "Unzipping " + ze.getName());
if (ze.isDirectory()) {
dirChecker(destination, ze.getName());
} else {
File f = new File(destination, ze.getName());
if (!f.exists()) {
boolean success = f.createNewFile();
if (!success) {
Log.w(TAG, "Failed to create file " + f.getName());
continue;
}
FileOutputStream fout = new FileOutputStream(f);
int count;
while ((count = zin.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
zin.closeEntry();
fout.close();
}
}
}
zin.close();
} catch (Exception e) {
Log.e(TAG, "unzip", e);
}
}
private static void dirChecker(String destination, String dir) {
File f = new File(destination, dir);
if (!f.isDirectory()) {
boolean success = f.mkdirs();
if (!success) {
Log.w(TAG, "Failed to create folder " + f.getName());
}
}
}
}
Maybe you should try using a FileOutputStream in combination with an inputstream from the zip file. With a package file, this should work.
To quote #wordy from this question:
PackageManager pm = context.getPackageManager();
String apkFile = pm.getApplicationInfo(context.getPackageName(), 0).sourceDir;
ZipFile zipFile = new ZipFile(apkFile);
ZipEntry entry = zipFile.getEntry("assets/FILENAME");
myInput = zipFile.getInputStream(entry);
myOutput = new FileOutputStream(file);
byte[] buffer = new byte[1024*4];
int length;
int total = 0;
int counter = 1;
while ((length = myInput.read(buffer)) > 0) {
total += length;
counter++;
if (counter % 32 == 0) {
publishProgress(total);
}
myOutput.write(buffer, 0, length);
}
Looks like there may be problems with ProGuard but hopefully the code sample works for you.
I haven't tested yet,but while doing a project on OCR I came across this library,where there is method of unzipping a downloaded file from the net. The exact method for unzipping file is installZipFromAssets(String sourceFilename,File destinationDir,File destinationFile) found under this class.Hope this is what you are looking for
You can also make use of the zip4j external library that provides additional features like encryption. Also, it has functions to extract files to a particular location provided the path.
I got following error when i try to unzip zip file
End-of-central-directory signature not found
I have also try 7zip lib, it works fine in simple java but in android platform.
I get a "dependent jar not found" error.
try {
// Initiate the ZipFile
ZipFile zipFile = new ZipFile(file);
String destinationPath = destPath;
// If zip file is password protected then set the password
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
//Get a list of FileHeader. FileHeader is the header information for all the
//files in the ZipFile
List fileHeaderList = zipFile.getFileHeaders();
// Loop through all the fileHeaders
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
if (fileHeader != null) {
//Build the output file
String outFilePath = destinationPath + System.getProperty("file.separator") + fileHeader.getFileName();
File outFile = new File(outFilePath);
//Checks if the file is a directory
if (fileHeader.isDirectory()) {
//This functionality is up to your requirements
//For now I create the directory
outFile.mkdirs();
continue;
}
//Check if the directories(including parent directories)
//in the output file path exists
File parentDir = outFile.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
//Get the InputStream from the ZipFile
is = zipFile.getInputStream(fileHeader);
//Initialize the output stream
os = new FileOutputStream(outFile);
int readLen = -1;
byte[] buff = new byte[BUFF_SIZE];
//Loop until End of File and write the contents to the output stream
while ((readLen = is.read(buff)) != -1) {
os.write(buff, 0, readLen);
}
//Please have a look into this method for some important comments
closeFileHandlers(is, os);
//To restore File attributes (ex: last modified file time,
//read only flag, etc) of the extracted file, a utility class
//can be used as shown below
UnzipUtil.applyFileAttributes(fileHeader, outFile);
System.out.println("Done extracting: " + fileHeader.getFileName());
} else {
System.err.println("fileheader is null. Shouldn't be here");
}
//File header always give error
You don't need 3rd party libraries when unzipping files in Android. Have a look at this:
http://www.jondev.net/articles/Unzipping_Files_with_Android_%28Programmatically%29
Its never too late i guess, using above caner unzipping is really too slow so i modified it
use following below class
package com.example.epubdemo;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.util.Log;
public class DecompressFast {
private String _zipFile;
private String _location;
public DecompressFast(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
bufout.close();
zin.closeEntry();
fout.close();
}
}
zin.close();
Log.d("Unzip", "Unzipping complete. path : " +_location );
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
Log.d("Unzip", "Unzipping failed");
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
USAGE
// save zip file in your internal storage directly not in any sub folder( if using any sub folder give below path correctly)
String zipFile = Environment.getExternalStorageDirectory() + "/the_raven.zip"; //your zip name
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzippedtestNew/"; //your unzip directory name
DecompressFast df= new DecompressFast(zipFile, unzipLocation);
df.unzip();
DONT FORGET TO GIVE READ AND WRITE PERMISSIONS
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
How to create a file, write data into it and read data from it on Android? If possible provide a code snippet.
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
From here: http://www.anddev.org/working_with_files-t115.html
//Writing a file...
try {
// catches IOException below
final String TESTSTRING = new String("Hello Android");
/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(TESTSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
//Reading the file back...
/* We have to use the openFileInput()-method
* the ActivityContext provides.
* Again for security reasons with
* openFileInput(...) */
FileInputStream fIn = openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
/* Prepare a char-Array that will
* hold the chars we read back in. */
char[] inputBuffer = new char[TESTSTRING.length()];
// Fill the Buffer with data from the file
isr.read(inputBuffer);
// Transform the chars to a String
String readString = new String(inputBuffer);
// Check if we read back the same chars that we had written out
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading stuff", "success = " + isTheSame);
} catch (IOException ioe)
{ioe.printStackTrace();}
I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
String inputLine = "";
/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/
FileInputStream fIn = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
try {
/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/
FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />