栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

以相反的顺序逐行读取文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

以相反的顺序逐行读取文件

[编辑]

根据要求,我将在稍后的评论中添加此答案:如果您经常需要此行为,则“更合适的”解决方案可能是使用DBAppender将日志从文本文件移动到数据库表(log4j
2的一部分)。然后,您可以简单地查询最新条目。

[/编辑]

与列出的答案相比,我可能会略有不同。

(1)创建一个子类,

Writer
该子类以相反的顺序写入每个字符的编码字节:

public class ReverseOutputStreamWriter extends Writer {    private OutputStream out;    private Charset encoding;    public ReverseOutputStreamWriter(OutputStream out, Charset encoding) {        this.out = out;        this.encoding = encoding;    }    public void write(int ch) throws IOException {        byte[] buffer = this.encoding.enpre(String.valueOf(ch)).array();        // write the bytes in reverse order to this.out    }    // other overloaded methods}

(2)创建log4j

WriterAppender
的子类,该子类的
createWriter
方法将被覆盖以创建的实例
ReverseOutputStreamWriter

(3)创建一个log4j

Layout
的子类,其
format
方法以相反的字符顺序返回日志字符串:

public class ReversePatternLayout extends PatternLayout {    // constructors    public String format(LoggingEvent event) {        return new StringBuilder(super.format(event)).reverse().toString();    }}

(4)修改我记录配置文件发送日志消息到 两个
“正常”的日志文件和“反向”的日志文件。“反向”日志文件将包含与“正常”日志文件相同的日志消息,但是每条消息将向后写入。(请注意,“反向”日志文件的编码不一定符合UTF-8甚至任何字符编码。)

(5)创建一个

InputStream
包装的实例的子类,
RandomAccessFile
以便以相反的顺序读取文件的字节:

public class ReverseFileInputStream extends InputStream {    private RandomAccessFile in;    private byte[] buffer;    // The index of the next byte to read.    private int bufferIndex;    public ReverseFileInputStream(File file) {        this.in = new RandomAccessFile(File, "r");        this.buffer = new byte[4096];        this.bufferIndex = this.buffer.length;        this.in.seek(file.length());    }    public void populateBuffer() throws IOException {        // record the old position        // seek to a new, previous position        // read from the new position to the old position into the buffer        // reverse the buffer    }    public int read() throws IOException {        if (this.bufferIndex == this.buffer.length) { populateBuffer(); if (this.bufferIndex == this.buffer.length) {     return -1; }        }        return this.buffer[this.bufferIndex++];    }    // other overridden methods}

现在,如果我想以相反的顺序读取“正常”日志文件的条目,我只需要创建一个实例

ReverseFileInputStream
,将其赋予“
revere”日志文件。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452570.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号