我希望能夠幫助我解決文件創建/響應問題。 我知道如何創建和保存文件。我知道如何通過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);
不是將數據保存到文件中,然後讀取文件並傳輸字節,只需剪掉中間人即可 - 將字節發送到客戶端,而不先將其保存到文件中。 – Deco 2011-12-21 23:17:41
謝謝德科。我認爲我的問題沒有得到很好的問。你的評論正是我想要做的,但我不知道該怎麼做。 – LatinCanuck 2011-12-22 15:28:08