オンライン ストリームをローカルに保存し、ローカル ノードからストリームを配信しようとしています。
プログラムの流れ:
最初の URL 要求 url-test は、ファイル名 url-file でファイル システムへの書き込みを開始する単一のライター スレッドを作成します。その 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();
}
}
}
次のリクエストでは、ローカルに保存されたファイル url-file を読み取り、最後に保存された位置に移動する必要があります。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();
}
出力が表示されません。別のスレッドによって更新されているファイルを検索する最良の方法は何ですか。
EDIT:ライタースレッドがファイルへの書き込みを継続し、リクエストに対する応答がその時点から開始されることを期待しています。一言で言えば、ファイル チャネルで位置を設定するときに、ライター スレッドはまだファイルに書き込みを行っています。ファイル チャネルの位置を 25% 少なく設定しても、inc.position(totalBytes - (long) 0.25 * totalBytes)
まだ出力が表示されません。