读取带有换行符的转义字符的Java文件 [英] Reading java file with escape characters for newline

查看:433
本文介绍了读取带有换行符的转义字符的Java文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Unicode文件,需要将其导出到数据库(Vertica).列定界符为CTRL + B,记录定界符为换行符(\ n).只要列值中有换行符,就将CTRL + A用作转义符.

I have a Unicode file that needs to be exported to database(Vertica). The column delimiter is CTRL+B, record delimiter is newline(\n). Whenever there is a newline within a column value, CTRL+A is used as escape character.

当我使用BufferedReader.readLine()读取此文件时,ID为2和4的记录被读取为两个记录.而我想将它们作为输出中给出的单个完整记录读取.

When I use BufferedReader.readLine() to read this file, the records with ID's 2 and 4, are read as two records. Whereas I want to read them as a single whole record as given in output.

这是示例输入文件. |代表CTRL + B,^代表CTRL + A.

Here is the example input file. | stands for CTRL+B and ^ stands for CTRL+A.

Input
ID|Name|Job Desc
----------------
1|xxxx|SO Job
2|YYYY|SO Careers^
Job
3|RRRRR|SO
4|ZZZZ^
 ZZ|SO Job
5|AAAA|YU

Output:
ID|Name|Job Desc
----------------
1|xxxx|SO Job
2|YYYY|SO Careers Job
3|RRRRR|SO
4|ZZZZ ZZ|SO Job
5|AAAA|YU

文件很大,所以我不能使用StringEscapeUtils.有什么建议吗?

The file is huge, so I cant use StringEscapeUtils. Any suggestions on this?

推荐答案

您可以将Scanner与自定义分隔符一起使用.我使用的分度符设置为匹配\n,但不匹配 \u0001\n(其中\u0001代表CTRL+A):

You can use a Scanner with a custom delimeter. The delimeter I use is set to match \n but not \u0001\n (where \u0001 represents CTRL+A):

try {
    PrintWriter writer = new PrintWriter("dboutput.txt");
    Scanner sc = new Scanner(new File("dbinput.txt"));
    sc.useDelimiter(Pattern.compile("^(?!.*(\\u0001\\n)).*\\n$"));
    while (sc.hasNext()) {
        writer.println(sc.next());
    }
    scanner.close();
    writer.close();
} catch (FileNotFoundException e) {
   e.printStackTrace();
} 

这篇关于读取带有换行符的转义字符的Java文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆