我正在使用JSCH尝试在不断更新的单独服务器上读取日志文件。我可以选择文件中当前的内容,但是一旦到达文件末尾,就会发生延迟,但是没有出现新行,并且延迟打印语句继续循环(我通过在记录我的程序)。如果有人可以指出我的代码中可能存在的错误或遗漏之处,或者提出了更好的方法,我将不胜感激。
InputStream stream = sftpClient.get(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line;
while (true)
{
try
{
line = br.readLine();
if (line == null)
{
System.out.println("End of file reached. Sleeping..");
Thread.sleep(sleepTime);
System.out.println("Retrying for more data..");
}
else
{
//do something with line, print for now.
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println("Something went wrong: " + e);
}
}
您可以看到Jsch的ChannelSftp
here的源代码。当您读取到远程文件的末尾时,获取远程文件时的InputStream returned by jsch会设置一个标志。继续尝试从流中读取将仅返回缓存的EOF指示。
Jsch具有a stat()
method to retrieve information about a remote file,包括其大小和最后修改的时间戳。 Jsch还具有stat()
,可让您跳过远程文件的第一部分。您可以定期调用stat()来检测文件是否已更改,然后使用get()跳过文件中已经读取的部分,而只是读取新内容。
您可能还考虑使用其他SSH客户端库。 a version of the get method包含用于打开远程文件以及读取或写入文件的任意部分的低级命令。但是,Jsch并未通过ChannelSftp公开此功能的全部范围。还有其他Java SFTP客户端库可提供对SFTP协议的较低级别的访问。
我认为您应该在结束时重新打开文件。如果是出于生产目的,请尝试使用Apache tailerSFTP protocol
仅补充crv所提到的内容,这是一个有关如何使用Apache https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/Tailer.html的示例
Tailor
[我正在尝试这种情况,我必须连续读取日志,但是我只能通过sftp访问它,正如@Kenster提到的那样,我通过调用import java.io.File;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;
import org.apache.commons.io.input.TailerListenerAdapter;
public class FileTailor {
private static final int SLEEP = 500;
public static void main(String[] args) throws Exception {
FileTailor fileTailor = new FileTailor();
fileTailor.run("log_file.log");
}
private void run(String path) throws InterruptedException {
TailerListener listener = new LogFileListener();
Tailer tailer = Tailer.create(new File(path), listener, SLEEP);
tailer.run();
}
public class LogFileListener extends TailerListenerAdapter {
@Override
public void handle(String line) {
//do something with line, print for now.
System.out.println(line);
}
}
}
检查文件的大小是否已更改,然后使用stat()
的作用是在我的目录中生成一个新文件,并使用get( String src, String dst, SftpProgressMonitor monitor, int mode)
中的mode参数,仅获取最新内容。
RESUME