I have to read a file and then write something to some output file. In both input and output files, I used pipeline delimiter :-
private static final String COLUMNDELIMITER = "\\|";
I can read the input file perfectly but for the output file, the lines are coming as below:
abc\|123\|kk
But I want it to be:
abc|123|kk
Why the same delimiter behaving differently for read and write?
When I am reading a line, I am using:
String[] elements = record.split(COLUMNDELIMITER); //works perfect
And while writing I am using:
String lineToWrite = String1 + COLUMNDELIMITER + String2 + COLUMNDELIMITER + String3 //Does not work rightly
String.split
takes a regular expression, and a pipe ( |
) has special meaning, so it needs to be escaped. This is done using a backslash ( \\
), which needs to be escaped in Java strings, so you need to use double-backslash (\\) in the string literal. However, when concatenating, you just need |
, not \\|
.
So, instead use:
private static final String COLUMNDELIMITER = "|";
And when splitting, quote it using java.util.regex.Pattern#quote
:
String[] elements = record.split(Pattern.quote(COLUMNDELIMITER));
Your concatenation will then just work.
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.