Writing File object to another location - java

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.

Related

How to compress a folder and send via email in android

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.

How to copy file from one PC to another

I am trying this code to transfer file from my computer to another computer but i am getting
Exception java.io.FileNotFoundException: \192.168.1.4\D:\Color.txt (The network name cannot be found)
File source = new File("G:\\Color.txt");
File dest = new File("\\\\192.168.1.4\\D:\\Color.txt");
// File dest = new File("D:\\Color.txt");
try {
InputStream input = new FileInputStream(source);
OutputStream output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
System.out.println("File Copied successfully");
input.close();
output.close();
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
A file or a directory in the file system is represented by two abstract concepts in java. These abstract concepts are java.io.File and java.nio.file.Path.
The File class represents a file in the file system whereas the interface Path represents the path string of the file. In this tutorial we look at various operations on File or Path. We get a handle on the File using
Syntax :
File file = new File("c:\\filefolder\\file.txt");
But in your case first check whether location is available through file explorer,and use the same address.

Saving file generated from Java Code to user defined location like download Functionality

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 :)

Load and read a zip file with JFileChooser?

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.

How to use java.util.zip to archive/deflate string in java for use in Google Earth?

Use Case
I need to package up our kml which is in a String into a kmz response for a network link in Google Earth. I would like to also wrap up icons and such while I'm at it.
Problem
Using the implementation below I receive errors from both WinZip and Google Earth that the archive is corrupted or that the file cannot be opened respectively. The part that deviates from other examples I'd built this from are the lines where the string is added:
ZipEntry kmlZipEntry = new ZipEntry("doc.kml");
out.putNextEntry(kmlZipEntry);
out.write(kml.getBytes("UTF-8"));
Please point me in the right direction to correctly write the string so that it is in doc.xml in the resulting kmz file. I know how to write the string to a temporary file, but I would very much like to keep the operation in memory for understandability and efficiency.
private static final int BUFFER = 2048;
private static void kmz(OutputStream os, String kml)
{
try{
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(os);
out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
File f = new File("./icons"); //folder containing icons and such
String files[] = f.list();
if(files != null)
{
for (String file: files) {
LOGGER.info("Adding to KMZ: "+ file);
FileInputStream fi = new FileInputStream(file);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(file);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
ZipEntry kmlZipEntry = new ZipEntry("doc.kml");
out.putNextEntry(kmlZipEntry);
out.write(kml.getBytes("UTF-8"));
}
catch(Exception e)
{
LOGGER.error("Problem creating kmz file", e);
}
}
Bonus points for showing me how to put the supplementary files from the icons folder into a similar folder within the archive as opposed to at the same layer as the doc.kml.
Update Even when saving the string to a temp file the errors occur. Ugh.
Use Case Note The use case is for use in a web app, but the code to get the list of files won't work there. For details see how-to-access-local-files-on-server-in-jboss-application
You forgot to call close() on ZipOutputStream. Best place to call it is the finally block of the try block where it's been created.
Update: To create a folder, just prepend its name in the entry name.
ZipEntry entry = new ZipEntry("icons/" + file);

Categories