I have developed a program where I want to save different files to a zip as backup and then load them back when a restore button is clicked. I have the save file code below but how would I load this file with JFileChooser? I don't need to read it to the program just literally unzip it into the folder where my application is. How would I do this? My create zip code is below:
public void createZip(){
byte[] buffer = new byte[1024];
String[] srcFiles = {"Payments.dat", "PaymentsPosted.dat", "Receipts.dat", "ReceiptsPosted.dat", "AccountDetails.dat", "AssetsLiabilities.dat", "UnitDetails.dat"};
String zipFile = "Backups.zip";
try{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i=0; i < srcFiles.length; i++) {
File srcFile = new File(srcFiles[i]);
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}catch(IOException ex){
ex.printStackTrace();
}
JOptionPane.showMessageDialog(null,"File Saved! See Backups.zip in your program folder");
}
}
Also I would appreciate if someone could tell me how to also wrap the above method into a JFileChooser to save?
To create the JFileChooser, the code would look like this:
public void showOpenDialog() {
// Create a filter so that we only see .zip files
FileFilter filter = new FileNameExtensionFilter(null, "zip");
// Create and show the file filter
JFileChooser fc = new JFileChooser();
fc.setFileFilter(filter);
int response = fc.showOpenDialog(null);
// Check the user pressed OK, and not Cancel.
if (response == JFileChooser.APPROVE_OPTION) {
File yourZip = fc.getSelectedFile();
// Do whatever you want with the file
// ...
}
}
As far as actually unzipping the zipped files, you can find more info here.
Related
Everyone: I am trying to send a folder (there are many files inside this folder) via email in Android Development.
First, I tried send the whole folder directly by using a click event and intent event.
My first attempt code shows the following:
My first part of code is onclicklistener event:
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu,int index) {
switch (index) {
case 0:
sendEmail(list.get(position).getName());
break;
case 1:
list.remove(position);
adapter.notifyDataSetChanged();
}
return false;
}
});
My second code to send Email is as follows:
public void sendEmail(String data_path){
Intent email = new Intent(Intent.ACTION_SEND);
File file_location = new File(SDCard, data_path);
email.setType("vnd.android.cursor.dir/email");
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"example#gmail.com"}); //set up email
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file_location)); //add attachment
email.putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(email, "pick an Email provider"));
}
When I run this code, it works fine to jump into email sender, but without any folder implement, the email implement is empty.
I am wondering if it is impossible to send a folder directly via email.
Now I am trying to another way to solve this: I am planning to compress folder(.zip) first and then send the zip file to email in just one click event, But I can not find any solutions showing how to compress the folder and send zip file in just one click event, What I mean is that I want a solution which:
Clicks the file that needs to be sent (click event has finished)
After it triggers the click event, the app will compress the clicked file to a zip file.
The zip file will automatically add as mail implements that waits to be sent
I was trapped there for many days and still failed to find any answers, I also search on StackOverflow, but most questions are about how to compress a file or send file by email. I am looking for a way to compress a folder and send a zip file in one click event.
If you have any ideas, I would quite appreciate them!
Here is a workaround to transform your folder into zip.
First, grant permissions:
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And then use this to transform your folder:
/*
*
* Zips a file at a location and places the resulting zip file at the toLocation
* Example: zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
*/
public boolean zipFileAtPath(String sourcePath, String toLocation) {
final int BUFFER = 2048;
File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
Here is another example:
private static void zipFolder(String inputFolderPath, String outZipPath) {
try {
FileOutputStream fos = new FileOutputStream(outZipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(inputFolderPath);
File[] files = srcFile.listFiles();
Log.d("", "Zip directory: " + srcFile.getName());
for (int i = 0; i < files.length; i++) {
Log.d("", "Adding file: " + files[i].getName());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
zos.close();
} catch (IOException ioe) {
Log.e("", ioe.getMessage());
}
}
Also you can use this library to zip a folder or file.
Import the .jar into your project and then you can do this to transform what you need:
try {
File input = new File("path/to/your/input/fileOrFolder");
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "zippedItem.zip";
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_STORE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
File output = new File(destinationPath);
ZipFile zipFile = new ZipFile(output);
// .addFolder or .addFile depending on your input
if (sourceFile.isDirectory())
zipFile.addFolder(input, parameters);
else
zipFile.addFile(input, parameters);
// Your input file/directory has been zipped at this point and you
// can access it as a normal file using the following line of code
File zippedFile = zipFile.getFile();
} catch (ZipException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
This should do the trick.
My app is a tender document system where each tender number has one or more pdf files attached.
application is done in java ee using struts and mysql.
in a database table the paths of each related pdf file for a tender number is stores.
I want to get all the pdf files and create a single ZIP file for each tender number so that user can download that zip file and have all the related documents in a single click.
I tried Google and found something called ZipOutputStream but i cannot understand how to use this in my application.
You're almost there... This is a small example of how to use ZipOutputStream... let's asume that you have a JAVA helper H that returns database records with pdf file paths (and related info):
FileOutputStream zipFile = new FileOutputStream(new File("xxx.zip"));
ZipOutputStream output = new ZipOutputStream(zipFile);
for (Record r : h.getPdfRecords()) {
ZipEntry zipEntry = new ZipEntry(r.getPdfName());
output.putNextEntry(zipEntry);
FileInputStream pdfFile = new FileInputStream(new File(r.getPath()));
IOUtils.copy(pdfFile, output); // this method belongs to apache IO Commons lib!
pdfFile.close();
output.closeEntry();
}
output.finish();
output.close();
Checkout this code, here you can easily create a zip file directory:
public class CreateZipFileDirectory {
public static void main(String args[])
{
try
{
String zipFile = "C:/FileIO/zipdemo.zip";
String sourceDirectory = "C:/examples";
//create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File dir = new File(sourceDirectory);
if(!dir.isDirectory())
{
System.out.println(sourceDirectory + " is not a directory");
}
else
{
File[] files = dir.listFiles();
for(int i=0; i < files.length ; i++)
{
System.out.println("Adding " + files[i].getName());
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
}
zout.close();
System.out.println("Zip file has been created!");
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
I have a requirement where i have to save a file that i m generating using my java code and but as when i want to save it i want to let user decide where they want to save it.Like a download option that comes when we download a file from internet.I have tried using JFileChooser. But it does not work the way i want it to work.Can somebody please help.
Im creating the file like
try{
writer= new PrintWriter("F://map.txt", "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
JFrame parentFrame = new JFrame();
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
Writing to a file
Note that this will overwrite the file if it exists, and it will not automatically prompt you for sh*t if it does. You have to check if it exists by yourself.
byte dataToWrite[] = // source
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(dataToWrite);
out.close();
In your case this would probably read out as
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(fileToSave.getPath());
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
Please note that this is untested code and I have no real routine with this stuff. You should google "java write file" or something like that if this proves to be erronous code :)
I am trying to create a zip file of multiple image files. I have succeeded in creating the zip file of all the images but somehow all the images have been hanged to 950 bytes. I don't know whats going wrong here and now I can't open the images were compressed into that zip file.
Here is my code. Can anyone let me know what's going here?
String path="c:\\windows\\twain32";
File f=new File(path);
f.mkdir();
File x=new File("e:\\test");
x.mkdir();
byte []b;
String zipFile="e:\\test\\test.zip";
FileOutputStream fout=new FileOutputStream(zipFile);
ZipOutputStream zout=new ZipOutputStream(new BufferedOutputStream(fout));
File []s=f.listFiles();
for(int i=0;i<s.length;i++)
{
b=new byte[(int)s[i].length()];
FileInputStream fin=new FileInputStream(s[i]);
zout.putNextEntry(new ZipEntry(s[i].getName()));
int length;
while((length=fin.read())>0)
{
zout.write(b,0,length);
}
zout.closeEntry();
fin.close();
}
zout.close();
This is my zip function I always use for any file structures:
public static File zip(List<File> files, String filename) {
File zipfile = new File(filename);
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
// compress the files
for(int i=0; i<files.size(); i++) {
FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(files.get(i).getName()));
// transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
}
// complete the ZIP file
out.close();
return zipfile;
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Change this:
while((length=fin.read())>0)
to this:
while((length=fin.read(b, 0, 1024))>0)
And set buffer size to 1024 bytes:
b=new byte[1024];
I have chosen file using
File file = fileChooser.getSelectedFile();
Now I want to write this file chosen by user to another location when user clicks save button. How to achieve that using swing?
To select the file you need something like ,
JFileChooser open = new JFileChooser();
open.showOpenDialog(this);
selected = open.getSelectedFile().getAbsolutePath(); //selected is a String
...and to save a copy ,
JFileChooser save = new JFileChooser();
save.showSaveDialog(this);
save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String
new CopyFile(selected,tosave);
...the copyFile class will be something like,
public class CopyFile {
public CopyFile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Also have a look at this question : How to save file using JFileChooser? #MightBeHelpfull
Swing will just give you the location/File object. You are going to have to write the new file yourself.
To copy the file, I will point you to this question: Standard concise way to copy a file in Java?
If you are using JDK 1.7 you can use the java.nio.file.Files class which offers several copy methods to copy a file to a given destiny.
read the file into a InputStream and then write it out to an OutputStream.