I'm trying to download a zip file from a URL, and I have completed that. The problem is is that it keeps downloading the webpage itself, so I end up with some beautiful HTML, CSS, JS, and PHP. That's nowhere near a zip file.
Please correct me if I'm doing something wrong with my code:
private static String URL = "webpage/myzip.zip";
private static String OUTPUT_PATH = "path/to/extract/to";
private static File OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
public static void create() throws Exception {
if (!OUTPUT_DIRECTORY.exists()) OUTPUT_DIRECTORY.mkdirs();
else return;
System.out.println("Natives not found. Downloading.");
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(URL).openStream());
fout = new FileOutputStream(OUTPUT_PATH + File.separator + "myzip.zip");
final byte[] data = new byte[4096];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) in.close();
if (fout != null) fout.close();
}
OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
File zip = OUTPUT_DIRECTORY.listFiles()[0];
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zip));
ZipEntry ze = zipIn.getNextEntry();
byte[] buffer = new byte[4096];
while (ze != null) {
String fName = ze.getName();
File newFile = new File(OUTPUT_DIRECTORY + File.separator + fName);
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zipIn.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zipIn.getNextEntry();
}
zipIn.closeEntry();
zipIn.close();
// zip.delete();
System.out.println("Natives Downloaded.");
}
Answer provided by: Scary Wombat
I didn't copy the link correctly. I was using a drop box link, and I forgot that I needed to copy the download link from when you hit the download button.
Related
That's my android code which takes 30 min to copy a 3MB .log file into a .zip and gives lots of GC_FOR_ALLOC. I also tried to change buffersize from 1k to 8k
File tempFolder=new File(Environment.getExternalStorageDirectory()+LOG_FILE_DIRECTORY_TEMP);
String filePath= Environment.getExternalStorageDirectory()+LOG_FILE_DIRECTORY_TEMP+ "/";
String fileName ="";
String zipFileName="";
String date=DATE_FORMAT_TEMP.format(new Date());
fileName = Settings.LOG_FILE_PREFIX + date+"_" + IMEI +.log;
zipFileName = Settings.LOG_FILE_PREFIX + date+"_" + IMEI +.zip;
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String result="";
String line = "";
while((line = br.readLine())!=null)
result += line;
result = getHeader() + result;
fos = new FileOutputStream(file);
fos.write(result.getBytes());
File zipFile=new File(filePath+zipFileName);
iStream = new FileInputStream(file);
oStream = new FileOutputStream(zipFile);
zos = new ZipOutputStream(oStream);
ze = new ZipEntry(fileName);
zos.putNextEntry(ze);
byte[] buffer = new byte[1024];
while((length = iStream.read(buffer)) != -1)
zos.write(buffer, 0, length);
zos.flush();
oStream.flush();
In your code it looks like you are opening and reading the file twice (your BufferedReader and your iStream object). Also, you are loading the entire file into memory twice before writing anything to memory. That's still only 6MB but you probably are hitting your memory stack limit - unless you use android:largeHeap="true" in your manifest.
Before you do that though, try just reading/writing each part:
public void zip(String[] _files, String zipFileName) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFileName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < _files.length; 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();
}
}
Here is the reference: http://javatechig.com/android/how-to-programmatically-zip-and-unzip-file-in-android
My file unzips one folder and one file but does not unzip the rest for some reason. How can I make it so it unzips all of the zip files contents?
public void unzip(String filepath, String filename, String unzip_path) throws IOException {
InputStream is = new FileInputStream(filepath + filename);
Log.d("1st", filepath + filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
String filename_temp = ze.getName();
File fmd = new File(unzip_path + filename_temp);
Log.d("2nd", unzip_path + filename_temp);
if (!fmd.getParentFile().exists()) {
fmd.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(unzip_path + filename_temp);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
//}
}
} finally {
zis.close();
}
}
How to move file one directory to another directory using in java? Please let me know if any alternative solution to do this in java.
public class FileTransform
{
public static void copyFile(File sourceFile, File destFile) throws IOException
{
if (!destFile.exists())
{
destFile.createNewFile();
}
System.out.println("Copy File Method");
FileChannel source = null;
FileChannel destination = null;
try
{
source = new FileInputStream(sourceFile).getChannel();
System.out.println("Destination File :"+destFile);
destination = new FileOutputStream(destFile).getChannel();
// previous code: destination.transferFrom(source, 0, source.size());
// to avoid infinite loops, should be:
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size - count)) < size);
}
finally
{
if (source != null)
{
source.close();
}
if (destination != null)
{
destination.close();
}
}
}
public static void main(String[] args) throws IOException
{
FileTransform ft = new FileTransform();
File src= new File("C:/File/File1/A10301A0003174228I_20140528080958095/A10301A0003174228I.xml");
File dest= new File("E:/FileDest/File1");
ft.copyFile(src,dest);
}
}
Above code i am getting exception is
Exception in thread "main" java.io.FileNotFoundException: E:\FileDest\File1 (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at FileTransform.copyFile(FileTransform.java:22)
at FileTransform.main(FileTransform.java:48)
I am getting File not found exception, Please let me know how to do this in java
InputStream inStream = null;
OutputStream outStream = null;
File afile = new File("srcfilepath");
File bfile = new File("destfilepath");
inStream = new FileInputStream(srcfile);
outStream = new FileOutputStream(destfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}
Try This :
File yourFile= new File("C:/File/File1/A10301A0003174228I_20140528080958095/A10301A0003174228I.xml");
yourFile.renameTo(new File("E:/FileDest/File1/A10301A0003174228I.xml" ));
I successfully saved preferences in SharedPreferences. How can I save the preference file in sdcard and vice-versa ??? {I want to give option to the user to backup, so that he can save and load preferences across re-intallations}
To store the sharedpreference in the sdcard you can try
private void backup(Context context) {
File root = context.getFilesDir();
File parent = root.getParentFile();
File[] files = parent.listFiles();
File[] tmp = null;
for (File file : files) {
if (file.isDirectory()) {
tmp = file.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().contains("your_shared_preference_file_name");
}
});
if (tmp != null && tmp.length == 1) {
break;
}
}
}
File file = null;
if (tmp.length == 1) {
parent = tmp[0].getParentFile();
file = new File(Environment.getExternalStorageDirectory(), "tmp.xml");
FileInputStream fis = new FileInputStream(tmp[0]);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[32768];
int count = 0;
while ((count = fis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
}
}
Finally got time to finish the project
Since I used one preference file to save the user data, this is the code that I used to copy it.
File fileSrc = new File(filePath, "userdata.xml");
File fileDes = new File("/data/data/com.nik/shared_prefs/", "userdata.xml");
...
...
private void copyFileToShared(File fileSrc, File fileDes) {
FileInputStream fileinputstream=null;
FileOutputStream fileoutputstream=null;
try {
fileinputstream = new FileInputStream(fileSrc);
fileoutputstream = new FileOutputStream(fileDes);
byte[] buffer = new byte[4096];
int count = 0;
while ((count = fileinputstream.read(buffer)) > 0) {
fileoutputstream.write(buffer, 0, count);
}
fileinputstream.close();
fileoutputstream.flush();
fileoutputstream.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
And the file is copied... :-)
I'm trying to extract .zip files and I'm using this code:
String zipFile = Path + FileName;
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
UnzipCounter++;
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(Path
+ ze.getName());
while ((Unziplength = zin.read(Unzipbuffer)) > 0) {
fout.write(Unzipbuffer, 0, Unziplength);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
but the problem is that, while debugging, when the code reaches the while(!=null) part, the zin.getNextEntry() is always null so it doesnt extract anything..
The .zip file is 150kb.. How can I fix this?
The .zip exists
Code I use to dl the .zip:
URL=intent.getStringExtra("DownloadService_URL");
FileName=intent.getStringExtra("DownloadService_FILENAME");
Path=intent.getStringExtra("DownloadService_PATH");
File PathChecker = new File(Path);
try{
if(!PathChecker.isDirectory())
PathChecker.mkdirs();
URL url = new URL(URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
lenghtOfFile/=100;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Path+FileName);
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
total += count;
notification.setLatestEventInfo(context, contentTitle, "جاري تحميل ملف " + FileName + " " + (total/lenghtOfFile), contentIntent);
mNotificationManager.notify(1, notification);
}
output.flush();
output.close();
input.close();
You might have run into the following problem, which occurs, when reading zip files using a ZipInputStream: Zip files contain entries and additional structure information in a sequence. Furthermore, they contain a registry of all entries at the very end (!) of the file. Only this registry does provide full information about the correct zip file structure. Therefore, reading a zip file in a sequence, by using a stream, sometimes results in a "guess", which can fail. This is a common problem of all zip implementations, not only for java.util.zip. Better approach is to use ZipFile, which determines the structure from the registry at the end of the file. You might want to read http://commons.apache.org/compress/zip.html, which tells a little more details.
If the Zip is placed in the same directory as this exact source, named "91.zip", it works just fine.
import java.io.*;
import java.util.zip.*;
class Unzip {
public static void main(String[] args) throws Exception {
String Path = ".";
String FileName = "91.zip";
File zipFile = new File(Path, FileName);
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
int UnzipCounter = 0;
while ((ze = zin.getNextEntry()) != null) {
UnzipCounter++;
//if (ze.isDirectory()) {
// dirChecker(ze.getName());
//} else {
byte[] Unzipbuffer = new byte[(int) pow(2, 16)];
FileOutputStream fout = new FileOutputStream(
new File(Path, ze.getName()));
int Unziplength = 0;
while ((Unziplength = zin.read(Unzipbuffer)) > 0) {
fout.write(Unzipbuffer, 0, Unziplength);
}
zin.closeEntry();
fout.close();
//}
}
zin.close();
}
}
BTW
what is the language in that MP3, Arabic?
I had to alter the source to get it to compile.
I used the File constructor that takes two String arguments, to insert the correct separator automatically.
Try this code:-
private boolean extractZip(String pathOfZip,String pathToExtract)
{
int BUFFER_SIZE = 1024;
int size;
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(pathToExtract);
if(!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(pathOfZip), BUFFER_SIZE));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = pathToExtract +"/"+ ze.getName();
if (ze.isDirectory()) {
File unzipFile = new File(path);
if(!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
}
else {
FileOutputStream out = new FileOutputStream(path, false);
BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
try {
while ( (size = zin.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
fout.write(buffer, 0, size);
}
zin.closeEntry();
}catch (Exception e) {
Log.e("Exception", "Unzip exception 1:" + e.toString());
}
finally {
fout.flush();
fout.close();
}
}
}
}catch (Exception e) {
Log.e("Exception", "Unzip exception2 :" + e.toString());
}
finally {
zin.close();
}
return true;
}
catch (Exception e) {
Log.e("Exception", "Unzip exception :" + e.toString());
}
return false;
}
This code works fine for me. Perhaps you need to check that the zipFile String is valid?
String zipFile = "C:/my.zip";
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("got entry " + ze);
}
zin.close();
produced valid results on a 3.3Mb zip file.
This code seems to work correctly for me.
Are you sure that your zip file is a valid zip file? If the file does not exist or is not readable then you will get a FileNotFoundException, but if the file is empty or not a valid zip file, then you will get ze == null.
while ((ze = zin.getNextEntry()) != null) {
The zip that you specify isn't a valid zip file. The size of the entry is 4294967295
while ((ze = zin.getNextEntry()) != null) {
System.out.println("ze=" + ze.getName() + " " + ze.getSize());
UnzipCounter++;
This gives:
ze=595.mp3 4294967295
...
Exception in thread "main" java.util.zip.ZipException: invalid entry size (expected 4294967295 but got 341297 bytes)
at java.util.zip.ZipInputStream.readEnd(ZipInputStream.java:386)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:156)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at uk.co.farwell.stackoverflow.ZipTest.main(ZipTest.java:29)
Try your code with a valid zip file.
I know it's late for answer but anyway ..
I think the problem is in
if(!PathChecker.isDirectory())
PathChecker.mkdirs();
it should be
if(!PathChecker.getParentFile().exists())
PathChecker.getParentFile().mkdirs();