关于我以前的question,我发现maven无法真正输出jboss控制台。所以我想我想解决它。这是交易:
当jboss正在运行时,它会将控制台日志写入server.log文件,因此我正在尝试检索数据,因为每隔几秒钟文件就会被jboss更改/更新我遇到了一些困难所以我需要帮助。
我真正需要的是:
这是我到目前为止的代码,它有一个问题,它无限期运行,每次从文件的开头开始,我希望它继续从server.log打印新行。希望它在某些意义上是代码:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
for(;;){ //run indefinitely
// Open the file
FileInputStream fstream = new FileInputStream("C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
根据Montecristo的建议,我这样做了:
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
// Read File Line By Line
while ((line = br.readLine()) != null) {
// Print the content on the console
line = br.readLine();
if (line == null) {
Thread.sleep(1000);
} else {
System.out.println(line);
}
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
它仍然不起作用,它只是打印原始文件..虽然文件不断变化但没有任何事情发生..除原始日志文件外没有任何内容被打印出来。
这是解决方案: tnx Montecristo
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream(
"C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while (true) {
line = br.readLine();
if (line == null) {
Thread.sleep(500);
} else {
System.out.println(line);
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
另见:
http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html
答案 0 :(得分:2)
我不知道你是否朝着正确的方向前进,但如果我理解正确,你会觉得这很有用:java-io-implementation-of-unix-linux-tail-f
答案 1 :(得分:1)
您可以使用RandomAccessFile。
import java.io.IOException;
import java.io.RandomAccessFile;
public class LogFileReader {
public static void main( String[] args ) {
String fileName = "abc.txt";
try {
RandomAccessFile bufferedReader = new RandomAccessFile( fileName, "r"
);
long filePointer;
while ( true ) {
final String string = bufferedReader.readLine();
if ( string != null )
System.out.println( string );
else {
filePointer = bufferedReader.getFilePointer();
bufferedReader.close();
Thread.sleep( 2500 );
bufferedReader = new RandomAccessFile( fileName, "r" );
bufferedReader.seek( filePointer );
}
}
} catch ( IOException | InterruptedException e ) {
e.printStackTrace();
}
}
}