2011-12-21 16 views
4

我希望能夠幫助我解決文件創建/響應問題。 我知道如何創建和保存文件。我知道如何通過ServletOutputStream將該文件發回給用戶。Java servlet和IO:創建文件而不保存到磁盤並將其發送給用戶

但我需要的是創建一個文件,而不保存在磁盤上,然後通過ServletOutputStream發送該文件。

上面的代碼解釋了我有的部分。任何幫助讚賞。提前致謝。

// This Creates a file 
// 
String text = "These days run away like horses over the hill"; 
File  file = new File("MyFile.txt"); 
Writer writer = new BufferedWriter(new FileWriter(file)); 
writer.write(text); 
writer.close(); 

// Missing link goes here 
// 

// This sends file to browser 
// 
InputStream inputStream = null; 
inputStream = new FileInputStream("C:\\MyFile.txt"); 

byte[] buffer = new byte[8192]; 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

int bytesRead; 
while ( (bytesRead = inputStream.read(buffer)) != -1) 
    baos.write(buffer, 0, bytesRead); 

response.setContentType("text/html"); 
response.addHeader("Content-Disposition", "attachment; filename=Invoice.txt"); 

byte[] outBuf = baos.toByteArray(); 
stream = response.getOutputStream(); 
stream.write(outBuf); 
+3

不是將數據保存到文件中,然後讀取文件並傳輸字節,只需剪掉中間人即可 - 將字節發送到客戶端,而不先將其保存到文件中。 – Deco 2011-12-21 23:17:41

+0

謝謝德科。我認爲我的問題沒有得到很好的問。你的評論正是我想要做的,但我不知道該怎麼做。 – LatinCanuck 2011-12-22 15:28:08

回答

11

你並不需要保存過一個文件,只是使用的ByteArray流,嘗試這樣的事情:

inputStream = new ByteArrayInputStream(text.getBytes());

甚至更​​簡單,只是做:

stream.write(text.getBytes());

由於cHao建議使用text.getBytes("UTF-8")或類似的東西來指定一個字符集,而不是系統默認。可用的字符集列表可在Charset的API文檔中找到。

+2

例如,指定一個編碼,當然是......'text.getBytes(「UTF-8」)'。 – cHao 2011-12-21 23:26:16

+0

你的答案效果很好。謝謝你,先生! – LatinCanuck 2011-12-22 15:23:27

相關問題