简体   繁体   中英

Parse text file tags as xml - Java

I have a logs text file consists of several tags like the following:

<log level="info" id="12144" ....> <msg> test msg </msg> </log>

I want to parse this file, therefore I thought that since it looks like XML I can add the xml ( <?xml version="1.0"? >) and a root ( <file> ) tags to the file and then parse it with DOM Parser.

But currently, I am facing an issue to add text at the beginning of the file, since all available options are to overwrite, or to copy the original file to a temporary location and then add the intended text, which is not applicable for me as I am dealing with files bigger than 100 MB.

I use the below code to try to add the text at the beginning, and I tried several solutions or classes other than RandomAccessFile

RandomAccessFile RAF = new RandomAccessFile(file, "rw");
        RAF.getChannel().position(0);

        RAF.write(("<?xml version=\"1.0\" encoding=\"UTF-8\"?> \r\n <file> \r\n").getBytes()); 

        RAF.close();

Do you have any suggestions to add the text at the beginning or to parse the text file as it is and extract elements?

THanks,

如果您知道条目的精确模式, 如果该模式不会再更改它的相对容易提取使用正则表达式,如条目:

"<log *level=\"([^\"]*)\" *id=\"([^\"])\" *> ..."

Can't you just get the content of the file as String or Stream or whatever and then add your stuff to the beginning? After that you still can parse the document String/Stream whatever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM