簡體   English   中英

Java將數據寫入文件並下載嗎?

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

我是Java的新手,面臨桌面應用程序的問題。 我必須寫入數據並將其輸出為“data.txt”(意味着不將文件寫入固定位置)並讓用戶下載此文件。 我在互聯網上搜索了很多,但沒有得到任何適當的解決方案。 歡迎所有建議。

注意:我使用的是NetBeans IDE 7.0.1

將數據保存在流中,然后顯示FileChooser對話框,讓用戶決定將文件保存到的位置。 然后將流寫入選定的文件。

有關文件選擇器的更多信息,請訪問: http//docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

在服務器上創建文件后,您可以執行類似的操作,將圖像文件發送給客戶端(在我的情況下,它是一個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);
    }
}

這些是它使用的進口:

import org.apache.commons.codec.binary.Base64OutputStream;

import org.apache.commons.io.IOUtils;

在客戶端(在您的桌面應用程序中),您將使用相同的IOUtilsBase64解碼它,然后您可以將它存儲在任何您想要的地方。 對於這一點,@ Matten給出了一個簡潔的解決方案(+1)。

我有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