Java 查看文件以进行修改,并获取要添加的内容

Java 查看文件以进行修改,并获取要添加的内容,java,Java,我知道Java7中的WatchService,但我需要插入到文件中的添加内容。我该怎么做 例如:我有一个日志文件,我想查看并检查添加到该文件中的日志条目 如果程序退出(例如JVM崩溃),是否有办法继续监视?存储文件指针或类似文件 非常感谢你的帮助 V.以下代码应该能够满足您的要求。虽然它有点长,可能需要一些重构,但它应该是开箱即用的。我在字里行间插入了我的评论,必要时可以进一步解释 您只需要创建“/tmp/log.txt”文件,执行代码并向文件中添加一些内容。文件保存后,内容将显示在Java控制

我知道Java7中的WatchService,但我需要插入到文件中的添加内容。我该怎么做

例如:我有一个日志文件,我想查看并检查添加到该文件中的日志条目

如果程序退出(例如JVM崩溃),是否有办法继续监视?存储文件指针或类似文件

非常感谢你的帮助

V.

以下代码应该能够满足您的要求。虽然它有点长,可能需要一些重构,但它应该是开箱即用的。我在字里行间插入了我的评论,必要时可以进一步解释

您只需要创建“/tmp/log.txt”文件,执行代码并向文件中添加一些内容。文件保存后,内容将显示在Java控制台上

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class FileWatcher {

    private static final String POINTER_FILE_PATH = "/tmp/pointer.txt";

    private static final String LOG_FILE_PATH = "/tmp/log.txt";

    public static void main(String[] args) throws IOException,
            InterruptedException {
        File logFile = new File(LOG_FILE_PATH);

        //read the previous position in the log file
        long pointer = getLastPointer();

        while (true) {
            long fsize = logFile.length();

            // calculate the length of new content from the pointer position
            int length = (int) (fsize - pointer);

            if (length == 0) {
                // save CPU cycles if nothing happened in the log file
                Thread.sleep(100);
                continue;
            }

            if (fsize < pointer) {
                // throw exception if any file content has been deleted
                // (doesn't cater for caracter replacement)
                throw new RuntimeException("Tampered file content");
            }

            // initialise a new buffer for the new content
            byte[] buf = new byte[length];

            int actualLength = readFileContent(pointer, buf, length);

            // increment the position of the pointer in the file
            pointer = pointer + actualLength;

            //save the current pointer
            storePointer(pointer);

            // print out the new content
            System.out.print(new String(buf, 0, actualLength));
        }

    }

    private static int readFileContent(long pointer, byte[] buf, int length) throws IOException {
        // open a new input stream to the log file
        FileInputStream fis = new FileInputStream(LOG_FILE_PATH);

        try {
            // skip to the previous position in the log file
            fis.skip(pointer);

            // read file content into the buffer and retrieve the actual
            // number of bytes
            int actualLength = fis.read(buf, 0, length);
            return actualLength;
        } finally {
            fis.close();
        }
    }

    private static void storePointer(long pointer) throws IOException {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(POINTER_FILE_PATH);
            pw.write(String.valueOf(pointer));
            pw.flush();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    private static long getLastPointer() throws IOException {
        long pointer = 0;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(POINTER_FILE_PATH));
            String line = br.readLine();
            if (line != null && line.length() > 0) {
                pointer = Long.valueOf(line.trim());
            }
        } catch(IOException e) {
            pointer = 0;
        } finally {
            if (br != null)
                br.close();
        }

        return pointer;
    }

}
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileReader;
导入java.io.IOException;
导入java.io.PrintWriter;
公共类文件监视程序{
私有静态最终字符串指针文件路径=“/tmp/POINTER.txt”;
私有静态最终字符串日志文件路径=“/tmp/LOG.txt”;
公共静态void main(字符串[]args)引发IOException,
中断异常{
文件logFile=新文件(日志文件路径);
//读取日志文件中的上一个位置
长指针=getLastPointer();
while(true){
long fsize=logFile.length();
//从指针位置计算新内容的长度
int长度=(int)(fsize-指针);
如果(长度==0){
//如果日志文件中未发生任何事件,则保存CPU周期
睡眠(100);
继续;
}
if(fsize<指针){
//如果已删除任何文件内容,则引发异常
//(不适用于字符替换)
抛出新的RuntimeException(“篡改的文件内容”);
}
//为新内容初始化新缓冲区
字节[]buf=新字节[长度];
int actualLength=readFileContent(指针、buf、长度);
//增加指针在文件中的位置
指针=指针+实际长度;
//保存当前指针
存储指针(指针);
//打印出新内容
系统输出打印(新字符串(buf,0,实际长度));
}
}
私有静态int-readFileContent(长指针,字节[]buf,int-length)引发IOException{
//打开日志文件的新输入流
FileInputStream fis=新的FileInputStream(日志文件路径);
试一试{
//跳到日志文件中的上一个位置
fis.跳过(指针);
//将文件内容读入缓冲区并检索实际的
//字节数
int actualLength=fis.read(buf,0,长度);
返回实际长度;
}最后{
fis.close();
}
}
私有静态void storePointer(长指针)引发IOException{
PrintWriter pw=null;
试一试{
pw=新的PrintWriter(指针\文件\路径);
write(String.valueOf(指针));
pw.flush();
}最后{
如果(pw!=null){
关闭();
}
}
}
私有静态长getLastPointer()引发IOException{
长指针=0;
BufferedReader br=null;
试一试{
br=新的BufferedReader(新的文件读取器(指针\文件\路径));
String line=br.readLine();
if(line!=null&&line.length()>0){
指针=Long.valueOf(line.trim());
}
}捕获(IOE异常){
指针=0;
}最后{
如果(br!=null)
br.close();
}
返回指针;
}
}