I have a line in a file.txt, |a|b|c|d|
, that I want to extract the values between |
(result a,b,c,d
)
How can I do this?
Asked
Active
Viewed 94 times
-1

Alex
- 781
- 10
- 23

yasser101991
- 93
- 8
-
https://www.google.de/?gws_rd=ssl#safe=off&q=%22java+read+file+string%22+%22java+split+string%22 – Stefan Apr 22 '15 at 09:52
-
1`String[] array = filecontent.split("|");` – SaintLike Apr 22 '15 at 09:53
3 Answers
0
From String[] split(String regex)
Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
Use following code:
String[] arr = "|a|b|c|d|".split("\\|");

Sumit Singh
- 15,743
- 6
- 59
- 89
0
The pipe (|
) is a special character in regular expression language (the split method takes a regular expression as a parameter), and thus needs to be escaped.
You will need to use something like so: String[] str = "|a|b|c|d|".split("\\|");
Given this:
String[] str = "|a|b|c|d|".split("\\|");
for(String string : str)
System.out.println(string);
Will yield:
//The first string will be empty, since your string starts with a pipe.
a
b
c
d

npinti
- 51,780
- 5
- 72
- 96
0
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(new File(
"file.txt"));
BufferedReader br = new BufferedReader(fr);
String st;
StringBuffer sb = new StringBuffer();
st = br.readLine();
if (st != null) {
StringTokenizer strTkn = new StringTokenizer(st, "|");
while (strTkn.hasMoreElements()) {
sb.append(strTkn.nextElement());
}
}
System.out.println(sb);
}

Alok Pathak
- 875
- 1
- 8
- 20