简体   繁体   English

Java将数据写入文件并下载吗?

[英]Java write data to a file and download it?

I am new bi to Java, facing an issue with desktop application. 我是Java的新手,面临桌面应用程序的问题。 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. 我必须写入数据并将其输出为“data.txt”(意味着不将文件写入固定位置)并让用户下载此文件。 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 注意:我使用的是NetBeans IDE 7.0.1

Save the data in a stream and then display a FileChooser dialog to let the user decide where to save the file to. 将数据保存在流中,然后显示FileChooser对话框,让用户决定将文件保存到的位置。 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 有关文件选择器的更多信息,请访问: http//docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

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): 在服务器上创建文件后,您可以执行类似的操作,将图像文件发送给客户端(在我的情况下,它是一个JSP但客户端在哪里并不重要):

/**
 * 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.codec.binary.Base64OutputStream;

import org.apache.commons.io.IOUtils; 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. 在客户端(在您的桌面应用程序中),您将使用相同的IOUtilsBase64解码它,然后您可以将它存储在任何您想要的地方。 For this bit actually @Matten gives a neat solution (+1). 对于这一点,@ Matten给出了一个简洁的解决方案(+1)。

I have example with JFileChooser but sorry still didn't get your point about the download thing. 我有JFileChooser例子,但抱歉仍然没有得到关于下载的事情。

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM