Answer the question
In order to leave comments, you need to log in
How to create an infinite Java thread without using 100% CPU?
Good afternoon, I wrote a bot, in it I used the creation of three threads that work in endless
while(true){
}
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Paths;
public class LogReader implements Runnable{
private static String lastLogString = "defaultLast";
private static String sameMsgInLog = "defaultSame";
private static long prevLenght = 1;
private static File logFile = new File(String.valueOf(Paths.get("C:\\logs.txt")));
@Override
public void run() {
while (true){
if(logChanged()) {
System.out.println("лог изменен");
lastLogString = LogReader.readLog(logFile);
}
}
}
public static String readLog(File logFile){
String strToReturn = "default";
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(logFile, "r");
StringBuilder builder = new StringBuilder();
long length = logFile.length();
prevLenght = length;
length--;
length--;//структура лог файла такова, что после добавления новой строки, за ней следует пустая строка, а эти строки кода переносят указатели на нужную строку
randomAccessFile.seek(length);
for (long seek = length; seek >= 0; --seek) {
randomAccessFile.seek(seek);
char c = (char) randomAccessFile.read();
builder.append(c);
if(c == '\n'){
builder = builder.reverse();
strToReturn = builder.toString();
break;
}
}
} catch (Exception e) {
System.out.println("Ошибка при чтении файла");
}
return strToReturn;
}
public static String getLastLogString() {
if(lastLogString.equals(sameMsgInLog)){
return "pass";
}
sameMsgInLog = lastLogString;
return lastLogString;
}
public static boolean logChanged(){
if(prevLenght != logFile.length()){
return true;
}else{
return false;
}
}
}
Answer the question
In order to leave comments, you need to log in
Instead of asking for information about a file in an endless loop, you need to subscribe to a file change.
Then the OS itself will notify you that the file has changed.
https://docs.oracle.com/javase/7/docs/api/java/nio...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question