148 lines
2.7 KiB
Java
148 lines
2.7 KiB
Java
package fr.pandacube.java.logviewer;
|
|
|
|
import java.io.EOFException;
|
|
import java.io.File;
|
|
import java.io.FileNotFoundException;
|
|
import java.io.IOException;
|
|
import java.io.RandomAccessFile;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
import org.apache.commons.collections4.queue.CircularFifoQueue;
|
|
|
|
public class Main {
|
|
|
|
public static final String ANSI_RESET = "\u001B[0m";
|
|
|
|
public static final String ANSI_ERASE_SCREEN = "\u001B[2J";
|
|
public static final String ANSI_CURSOR_TOP_LEFT = "\u001B[1;1H";
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
if (args.length == 0) {
|
|
outln("1 argument attendu : le fichier à lire.");
|
|
return;
|
|
}
|
|
|
|
File f = new File(args[0]);
|
|
|
|
if (!f.exists()) {
|
|
outln("Le fichier spécifié n'existe pas");
|
|
return;
|
|
}
|
|
|
|
if (!f.isFile()) {
|
|
outln("Le fichier spécifié n'est pas un fichier régulier");
|
|
return;
|
|
}
|
|
|
|
CircularFifoQueue<String> lineBuffer = new CircularFifoQueue<>(100);
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
RandomAccessFile reader = new RandomAccessFile(f, "r");
|
|
try {
|
|
String line;
|
|
while ((line = readUTF8LineFromFile(reader)) != null) {
|
|
lineBuffer.add(line);
|
|
}
|
|
|
|
|
|
out(ANSI_ERASE_SCREEN+ANSI_CURSOR_TOP_LEFT);
|
|
|
|
while (!lineBuffer.isEmpty())
|
|
outln(lineBuffer.poll());
|
|
|
|
|
|
long previousLength = 0;
|
|
while(true) {
|
|
if ((line = readUTF8LineFromFile(reader)) != null) {
|
|
outln(line);
|
|
}
|
|
else {
|
|
previousLength = reader.length();
|
|
reader.close();
|
|
Thread.sleep(250);
|
|
|
|
// tant que l'exeption est lancée, on réessaye
|
|
for(;;) {
|
|
try {
|
|
reader = new RandomAccessFile(f, "r");
|
|
break;
|
|
} catch (FileNotFoundException e) {
|
|
Thread.sleep(250);
|
|
}
|
|
}
|
|
if (reader.length() >= previousLength)
|
|
reader.seek(previousLength);
|
|
}
|
|
|
|
}
|
|
|
|
} finally {
|
|
reader.close();
|
|
}
|
|
|
|
|
|
} catch (FileNotFoundException e) {
|
|
e.printStackTrace();
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
} catch (InterruptedException e) { }
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
public static String readUTF8LineFromFile(RandomAccessFile reader) {
|
|
List<Byte> bytes = new ArrayList<>();
|
|
|
|
byte b;
|
|
try {
|
|
for (;;) {
|
|
b = reader.readByte();
|
|
if ("\n".getBytes()[0] == b)
|
|
break;
|
|
|
|
bytes.add(b);
|
|
}
|
|
|
|
} catch (EOFException e) {
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
|
|
|
|
byte[] priBytes = new byte[bytes.size()];
|
|
for (int i=0; i<bytes.size(); i++)
|
|
priBytes[i] = bytes.get(i);
|
|
|
|
if (priBytes.length > 0)
|
|
return new String(priBytes);
|
|
|
|
return null;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static void outln(Object o) {
|
|
System.out.println(o);
|
|
}
|
|
public static void out(Object o) {
|
|
System.out.print(o);
|
|
}
|
|
|
|
|
|
|
|
}
|