token parsing in java

2020-07-30 02:01发布

I have created a file with printStream object as shown below.

PrintStream outPutOffice = new PrintStream(
   new BufferedOutputStream(new FileOutputStream(inDir+"/Office.txt")));
outPutOffice.print(fValue + (findx < agtOffColCount ? "|" : ""));   

Now I have to read it content and separate it tokens with "|" as I have written token with "|" separated. I have write code as shown below it will read line correctly but not separate token with "|" character.

BufferedReader inPutAgent = new BufferedReader(
   new InputStreamReader(new FileInputStream(inDir+"/Office.txt")));

String column=inPutAgent.readLine();
String []columnDetail = column.split("|");

columndetail array contains single character in each index instead i want single token in each index.

What is the problem?

标签: java
3条回答
放我归山
2楼-- · 2020-07-30 02:44

You should look into the StringTokenizer, it's a very handy tool for this types of work.

Example

 StringTokenizer st = new StringTokenizer("this is a test");
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }

This will putput

 this
 is
 a
 test

You use the Second Constructor for StringTokenizer to set the delimiter:

StringTokenizer(String str, String delim)

You could also use a Scanner as one of the commentators said this could look somewhat like this

Example

 String input = "1 fish 2 fish red fish blue fish";

 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());

 s.close(); 

The output would be

 1
 2
 red
 blue 

Meaning that it will cut out the word "fish" and give you the rest, using "fish" as the delimiter.

examples taken from the Java API

查看更多
狗以群分
3楼-- · 2020-07-30 02:48

The argument to split is a regex. You should do:

String []columnDetail = column.split("\\|");

or:

String []columnDetail = column.split("[|]");
查看更多
叼着烟拽天下
4楼-- · 2020-07-30 03:00

the split method works with regular expressions and since the pipe symbol (|) has a special meaning and is reserved, you need to escape it like this:

split("\\|");

You should read about regex here or here

查看更多
登录 后发表回答