简体   繁体   English

读取带换行符的转义java文件

[英]Reading java file with escape characters for newline

I have a Unicode file that needs to be exported to database(Vertica). 我有一个需要导出到数据库(Vertica)的Unicode文件。 The column delimiter is CTRL+B, record delimiter is newline(\\n). 列分隔符是CTRL + B,记录分隔符是换行符(\\ n)。 Whenever there is a newline within a column value, CTRL+A is used as escape character. 只要列值中有换行符,CTRL + A就会用作转义字符。

When I use BufferedReader.readLine() to read this file, the records with ID's 2 and 4, are read as two records. 当我使用BufferedReader.readLine()读取此文件时,ID为2和4的记录将被读取为两个记录。 Whereas I want to read them as a single whole record as given in output. 而我想将它们作为输出中给出的单个整体记录来阅读。

Here is the example input file. 这是示例输入文件。 | | stands for CTRL+B and ^ stands for CTRL+A. 代表CTRL + B,^代表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

The file is huge, so I cant use StringEscapeUtils. 该文件很大,所以我不能使用StringEscapeUtils。 Any suggestions on this? 有什么建议吗?

You can use a Scanner with a custom delimeter. 您可以将Scanner与自定义分隔符一起使用。 The delimeter I use is set to match \\n but not \\\n (where \ represents CTRL+A ): 我使用的分隔符设置为匹配\\n匹配\\n \\\n (其中\代表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();
} 

Tim is partially right in his answer. 蒂姆对他的回答部分正确。 But, it still does not resolve newlines escaped by CTRL+A. 但是,它仍然无法解决CTRL + A转义的换行符。

Here is my solution for that(guided by Tim answer) 这是我的解决方案(由Tim回答)

File f = new File("C:\\Users\\SV7104\\Desktop\\sampletest.txt");
Scanner sc = new Scanner(f).useDelimiter(Pattern.compile("\\s*\\u0002\\n\\s*"));
            while (sc.hasNext()) {
                System.out.print(1);
                System.out.println(sc.next().toString().replaceAll("\\u0001\\n", " "));

            }

If there's some other efficient method, I am curious to know about that too. 如果还有其他一些有效的方法,我很想知道这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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