Java write data to a file and download it?
-
07-06-2021 - |
Question
I am new bi to Java, facing an issue with desktop application. I have to write data and output it as "data.txt"(means without writing file to a fixed location) and let the user download this file. I had searched a lot over internet but didn't get any proper solution. All suggestions are welcome.
Note : I am using NetBeans IDE 7.0.1
Solution
Save the data in a stream and then display a FileChooser dialog to let the user decide where to save the file to. Then write the stream to the selected file.
More on file choosers can be read here: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
OTHER TIPS
Once you create your file on server you can then do a similar thing I did for sending image files to my clients (in my case it is a JSP
but it really doesn't matter where your client is):
/**
* Writes file with a given path to the response.
* @param pathToFile
* @param response
* @throws IOException if there was some problem writing the file.
*/
public static void writeFile(String pathToFile, ServletResponse response) throws IOException {
try(InputStream is = new FileInputStream(pathToFile);
OutputStream out = new Base64OutputStream(response.getOutputStream());){
IOUtils.copy(is, out);
}
}
Those are the imports it uses:
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.io.IOUtils;
On the client (in your desktop app) you would use the same IOUtils to decode it from Base64 and then you can store it wherever you want. For this bit actually @Matten gives a neat solution (+1).
I have example with JFileChooser
but sorry still didn't get your point about the download thing.
BufferedOutputStream buff = null;
BufferedReader reader = null;
JFileChooser fileChooser;
File file;
fileChooser.showSaveDialog(this);
file = new File(fileChooser.getSelectedFile().toString());
file.createNewFile();
reader = new BufferedReader(new StringReader("String text"));
buff = new BufferedOutputStream(new FileOutputStream(file));
String str;
while ((str = reader.readLine()) != null) {
buff.write(str.getBytes());
buff.write("\r\n".getBytes());
}