如何读取.logs文件中的最后一行?

huangapple 未分类评论53阅读模式
英文:

How to read the last line in a .logs document?

问题

基本上我有一个日志文件,它会被一个程序不断编辑。我想要检查聊天日志的最后一行是否始终包含"ONLINE:",如果是的话,我想将其保存为一个字符串。所以,每次如果日志中最后发送的消息包含单词"ONLINE:",字符串就会被编辑为包含"ONLINE:"的那一行。

我尝试在一个while(true)循环中始终创建一个ArrayList(因为文件会被编辑),其中包含整个.logs文件,并检查最后一条消息,但这种方法似乎不太奏效。有什么想法吗?

英文:

basically i have a logs file which gets edited by a Program all the time. I want to check if the Last Line of the Chatlogs includes a "ONLINE:" all the time and if it does, i'd like to save it as a String. So everytime if the last sent message in the logs includes the Word "ONLINE:" the string gets edited to the line including "ONLINE:".

I tried creating an ArrayList in a while(true)-Statement all the time (cause the file gets edited) with the whole .logs file and checking the last message but that kinda doesn't really work. Any Ideas?

答案1

得分: 0

如果这是您的代码编写到日志文件的部分,那么您只需更改记录日志的方法,使其在当前消息满足条件时同时执行其他操作。如果确实是这种情况,我还注意到了一些代码异味 - 基本上程序逻辑不应依赖于日志记录 - 所以如果您有(我假设的是)某种类似于handleReceivedNetworkMessage()的函数,您可以在其中进行处理(保存、筛选,或其他任何操作),然后作为最后一步进行日志记录。将日志记录视为调试的另一种手段。

另一方面,如果这不是您的程序写入日志文件的部分 - 也就是说,您只能访问文件系统中某个地方的.log文件,您可以使用java.nio.file中的WatchService注册事件,当文件被编辑时触发这些事件。

同时,思考一下您真正想在这种情况下做什么。在您的背景环境中,“将其保存为字符串”是什么意思?

英文:

IF this is your code that writes to the log file, then you could just change the method where you log to also do some other work if the current message meets your criteria. If that is indeed the case, then I also see some code smell - basically program's logic shouldn't depend on logging - so if you have (I assume) some kind of 'handleReceivedNetworkMessage()`, you do your work (save it, filter, whatever you want) and then as the last step log it. Think about logging as just another mean of debugging.

If on the other hand this isn't your program that writes to the log file - i.e. the only thing you have access to is a .log file somewhere on filesystem, you could use the WatchService from java.nio.file, to register events that get fired when a file is edited.

It may also be a good idea to think what do you really want to do with that kind of thing. What does "save it as a String" means in your context ?

huangapple
  • 本文由 发表于 2020年6月5日 21:30:46
  • 转载请务必保留本文链接:https://java.coder-hub.com/62216500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定