从txt文件中读取数据,尝试与正则表达式匹配,并将其作为XML(在xml文件中)存储在JAVA中

时间:2012-05-02 07:46:20

标签: java xml regex file

如何在Java中形成正则表达式,以便能够将匹配的数据直接存储为XML?

2 个答案:

答案 0 :(得分:1)

我会使用包装文本文件的Scanner类来实现。然后,使用适当的正则表达式创建Pattern对象。然后,您将能够将Pattern对象提供给Scanner实例并找到每个目标数据。最后,为了将这些数据保存为XML,我会使用JAXB来限制内存占用,因为您可能事先不知道有多少数据需要保存为XML。

答案 1 :(得分:0)

使用类似

的内容
public CharSequence fromFile(String filename) throws IOException {
        FileInputStream input = new FileInputStream(filename);
        FileChannel channel = input.getChannel();

        // Create a read-only CharBuffer on the file
        ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int)channel.size());
        CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
        return cbuf;
    }

并比较为:

try {
    // Create matcher on file
    Pattern pattern = Pattern.compile("pattern");
    Matcher matcher = pattern.matcher(fromFile("yourFile.txt"));

    // Find all matches
    while (matcher.find()) {
        // Get the matching string
        String match = matcher.group();
    }
} catch (IOException e) {
}