I have an application to download zip file and save to sdcard. But I get zipentry=null while reading inputstream, it doesn't enter the while block. Could anyone help me in solving this problem, please?
try {
// fileInputStream = new InputStream(input);
ZipInputStream zipInputStream
= new ZipInputStream(new BufferedInputStream(input));
ZipEntry zipEntry=zipInputStream.getNextEntry();
Toast.makeText(getApplicationContext(), "I have entered try block zipentry"+zipEntry,Toast.LENGTH_LONG).show();
System.out.println("Zipentry is"+zipEntry);
while ((zipEntry = zipInputStream.getNextEntry()) != null){
Toast.makeText(getApplicationContext(), "Entered into while block",Toast.LENGTH_LONG).show();
String zipEntryName = zipEntry.getName();
File file = new File(to + zipEntryName);
if (file.exists()){
} else {
if(zipEntry.isDirectory()){
file.mkdirs();
}else{
byte buffer[] = new byte[BUFFER_SIZE];
FileOutputStream fileOutputStream = new FileOutputStream(file);
bufferedOutputStream
= new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
int count;
while ((count
= zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
zipInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "File not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Input outout error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
You already have one ZipEntry zipEntry=zipInputStream.getNextEntry(); before condition in the while loop. Leave it out and initialize it only in the while loop. Something like:
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null){
//
}
Related
I am creating a custom print service in Android. When PDF is share to print service, it prints correctly but when image is shared it does not print as expected since it is corrupted. Below is method in my custom printservice. It saves PDF and image file. PDF file is fine and readable but image is corrupted after saved
private void handleHandleQueuedPrintJob(final PrintJob printJob) {
if (printJob.isQueued()) {
printJob.start();
}
int printType = printJob.getDocument().getInfo().getContentType();
if (printType == CONTENT_TYPE_DOCUMENT) {
String fName = MyHelper.getRandomString(8) + ".pdf";
File destFile = new File(getExternalFilesDir(MyConstants.FolderTemp), fName);
try {
InputStream in = new FileInputStream(printJob.getDocument().getData().getFileDescriptor());
FileOutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else if (printType == CONTENT_TYPE_PHOTO) {
String fName = MyHelper.getRandomString(8) + ".jpg";
File destFile = new File(getExternalFilesDir(MyConstants.FolderTemp), fName);
InputStream in = new FileInputStream(printJob.getDocument().getData().getFileDescriptor());
FileOutputStream out = null;
try {
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else
MyHelper.showLongToast(this, getString(R.string.invalidfiletype));
printJob.complete();
}
Can anybody help me why image is corrupted?
I want to install my app on android phone memory, if their is no enough space to installation then only it would install on external storage, but this all do programatically, not using
"android:installLocation= blahblah" in android manifest file.
so how should I do that?
use android:installLocation="internalOnly" in your manifest tag in manifest file.
Try below code for write .apk file in internal storage:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
PackageManager packageManager = context.getPackageManager();
String appname = resolveInfo .loadLabel(packageManager);
File apkfile = new File(
resolveInfo .activityInfo.applicationInfo.publicSourceDir);
File f = new File(Yourpath);
if (f.exists() && f.isDirectory()) {
try {
File outputFile = new File(f, appname + ".apk");
outputFile.createNewFile();
InputStream is = new FileInputStream(apkfile);
OutputStream out = new FileOutputStream(outputFile);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
is.close();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
f.mkdirs();
File outputFile = new File(f, appname + ".apk");
outputFile.createNewFile();
InputStream is = new FileInputStream(apkfile);
OutputStream out = new FileOutputStream(outputFile);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
is.close();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have .3gp audio file which is stored in SD Card.I want to copy that file into another folder of sd card.I have googled a lot about it but didn't get any working idea.Please help me if anyone knows.The code I have tried till now is given below:
private void save(File file_save) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/RecordedAudio";
File file_dir = new File(file_path);
if (file_dir.exists()) {
file_dir.delete();
}
file_dir.mkdirs();
File file_audio = new File(file_dir, "audio"
+ System.currentTimeMillis() + ".3gp");
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(file_save);
out.close();
FileOutputStream fos = new FileOutputStream(file_audio);
byte[] buffer = bos.toByteArray();
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is always create a new file with the size of 100.Thanks in advance...
The code when i call this save() method is:
mFileFirst = new File(mFileName);//mFileName is the path of sd card where .3gp file is located
save(mFileFirst);
Try this
private void save(File file_save) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/RecordedAudio";
File file_dir = new File(file_path);
if (file_dir.exists()) {
file_dir.delete();
}
file_dir.mkdirs();
File file_audio = new File(file_dir, "audio"
+ System.currentTimeMillis() + ".3gp");
try {
FileInputStream fis = new FileInputStream(file_save);
FileOutputStream fos = new FileOutputStream(file_audio);
byte[] buf = new byte[1024];
int len;
int total = 0;
while ((len = fis.read(buf)) > 0) {
total += len;
fos.write(buf, 0, len);
// Flush the stream once every so often
if (total > (20 * 1024)) {
fos.flush();
}
}
fos.flush();
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} 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();
}
How can I create a ZIP file from an XML file?
I want to take a backup of all my inbox messages in XML, and compress the XML file and store it on an SD card.
The following code solved my problem.
public class makeZip {
static final int BUFFER = 2048;
ZipOutputStream out;
byte data[];
public makeZip(String name) {
FileOutputStream dest=null;
try {
dest = new FileOutputStream(name);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out = new ZipOutputStream(new BufferedOutputStream(dest));
data = new byte[BUFFER];
}
public void addZipFile (String name) {
Log.v("addFile", "Adding: ");
FileInputStream fi=null;
try {
fi = new FileInputStream(name);
Log.v("addFile", "Adding: ");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("atch", "Adding: ");
}
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(name);
try {
out.putNextEntry(entry);
Log.v("put", "Adding: ");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count;
try {
while((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
//Log.v("Write", "Adding: "+origin.read(data, 0, BUFFER));
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("catch", "Adding: ");
}
try {
origin.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeZip () {
try {
out.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If you have a FOLDER in SDCard and you want to create a zip of it, then simply copy and paste this code in your project and it will give you a zip Folder. This code will create a zip of the folder which only contains files no nested folder should be inside. You can further modify for your self.
String []s=new String[2]; //declare an array for storing the files i.e the path of your source files
s[0]="/mnt/sdcard/Wallpaper/pic.jpg"; //Type the path of the files in here
s[1]="/mnt/sdcard/Wallpaper/Final.pdf"; // path of the second file
zip((s,"/mnt/sdcard/MyZipFolder.zip"); //call the zip function
public void zip(String[] files, String zipFile)
{
private String[] _files= files;
private String _zipFile= zipFile;
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.d("add:",_files[i]);
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
Also add permissions in android-manifest.xml using this code
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
You may take a look at this two links:
ZipOutputStream http://developer.android.com/reference/java/util/zip/ZipOutputStream.html
Zipping files http://www.jondev.net/articles/Zipping_Files_with_Android_%28Programmatically%29
Hope this helps
The Android SDK has the gZip API, by which you can read/write conpressed data. See public class GZIPOutputStream.
Use the following code, but if you want to save to the SD card, do a fileoutputstream rather than bytearrayoutputstream.
private String compressData(String uncompressedData) {
String compressedData = null;
try {
if (uncompressedData.length() > 200) {
// Perform Compression.
byte[] originalBytes = uncompressedData.getBytes();
Deflater deflater = new Deflater();
deflater.setInput(originalBytes);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
while (!deflater.finished()) {
int byteCount = deflater.deflate(buf);
baos.write(buf, 0, byteCount);
}
deflater.end();
byte[] compressedBytes = baos.toByteArray();
compressedData = new String(compressedBytes, 0, compressedBytes.length);
}
}
catch (Exception e) {
compressedData = null;
}
return compressedData;
}