gpt4 book ai didi

java - 文件在动态增加的文件中查找

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:53 24 4
gpt4 key购买 nike

我正在尝试在本地保存在线流,然后从本地节点分发该流。

程序流程:

对 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();
}

我没有看到任何输出,在文件中查找的最佳方法是什么,该文件正在由另一个线程更新。

编辑:我希望编写器线程继续写入文件,并且任何请求的响应都应该从该时间实例开始。简而言之,在设置文件 channel 中的位置时,我的编写器线程仍在写入文件。即使我将文件 channel 位置设置为 25%,例如 inc.position(totalBytes - (long) 0.25 * TotalBytes) 我仍然看不到输出。

最佳答案

在我看来,cv 保存文件中的总字节数。每次将数据追加到文件时,都会对 cv 进行更新调用。

第二个片段似乎使用相同的值(“文件大小”)作为文件 channel 中的标记。据我了解,您总是在文件的最后一个字节上设置标记,并尝试从该位置开始读取,显然,您会立即看到 EOF。

重新考虑计算响应起始位置的方法。它不应该是文件的最后一个字节。

关于java - 文件在动态增加的文件中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5576628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com