我試圖在本地保存在線流,然後從我的本地節點分發流。在一個動態增加的文件中尋找文件
程序流程:一個URL,URL測試
首先請求,創建一個單一的作家螺紋,其開始與文件名稱,網址,文件寫入到文件系統。所有後續對該URL的請求url-test都是從本地文件系統處理的。
寫線程
protected class Writer implements Runnable {
String url;
public void run() {
FileOutputStream out_file = null;
File cacheFile = new File("url-file");
byte[] buf = new byte[4096];
int count = 0;
try {
URL urlstream = new URL(url);
// cv is an object which stores url information
cv.originInputStream = urlstream.openStream();
out_file = new FileOutputStream(cacheFile);
while ((count = cv.originInputStream.read(buf)) > 0) {
out_file.write(buf, 0, count);
out_file.flush();
cv.incrementTotalBytes(count);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
現在爲下一個請求,我需要讀取本地保存的文件,鏈接文件,並移動到它上次保存的位置。我正在使用cv對象的totalBytes屬性,它給出了寫入器線程保存的總字節數。
FileInputStream in = new FileInputStream("url-file");
response.setHeader("Content-Disposition", "inline; filename="
+ localFile.getName());
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "-1");
OutputStream out = response.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[4096];
int count = 0;
FileChannel inc = in.getChannel();
ByteBuffer b = ByteBuffer.allocate(4096);
inc.position(cv.getTotalBytes());
while ((count = inc.read(b)) >= 0) {
out.write(b.array(), 0, count);
b.clear();
}
我沒有看到任何輸出,在另一個線程正在更新的文件中查找的最佳方式是什麼。
編輯:我期望作家線程繼續寫入文件,任何請求的響應應該從該時間實例開始。簡而言之,我的編寫器線程在文件通道中設置位置時仍在寫入文件。即使我將文件通道位置設置爲25%減少說inc.position(totalBytes - (long) 0.25 * totalBytes)
我仍然看不到輸出。
爲什麼在閱讀之前將'inc'的位置設置爲最後?如果在此期間文件不會被追加到後續讀取中,則不會返回任何內容。既然你想在隨後的請求中提供保存的文件,爲什麼不從0開始? – Thomas 2011-04-07 06:40:57
所以你只能提供部分文件?像不是整個HTML文檔,而只是自上次迭代以來作者追加的內容? – Thomas 2011-04-07 14:03:55
嗨托馬斯,我想從那個時間的實例開始。它就像一個活的飼料。我希望我的作家線程繼續寫入文件。增加了這個問題。 – Aman 2011-04-07 14:06:45