Java StringTokenizerの例
Javaでは、StringTokennizerクラスを使用して、定義された区切り文字によって文字列を異なるトークンに分割できます(スペースはデフォルトの区切り文字です)。 これが2つのStringTokennizer
の例です:
例1
StringTokennizer
を使用して、文字列を「スペース」と「コンマ」の区切り文字で分割し、StringTokenizer要素を繰り返して1つずつ出力します。
package com.example; import java.util.StringTokenizer; public class App { public static void main(String[] args) { String str = "This is String , split by StringTokenizer, created by example"; StringTokenizer st = new StringTokenizer(str); System.out.println("---- Split by space ------"); while (st.hasMoreElements()) { System.out.println(st.nextElement()); } System.out.println("---- Split by comma ',' ------"); StringTokenizer st2 = new StringTokenizer(str, ","); while (st2.hasMoreElements()) { System.out.println(st2.nextElement()); } } }
出力
---- Split by space ------ This is String , split by StringTokenizer, created by example ---- Split by comma ',' ------ This is String split by StringTokenizer created by example
例2
csvファイルを読み取り、StringTokenizerを使用して文字列を「|」区切り文字で分割し、出力します。
ファイル:c:/test.csv
1| 3.29| example 2| 4.345| eclipse
package com.example; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class ReadFile { public static void main(String[] args) { BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader("c:/test.csv")); while ((line = br.readLine()) != null) { System.out.println(line); StringTokenizer stringTokenizer = new StringTokenizer(line, "|"); while (stringTokenizer.hasMoreElements()) { Integer id = Integer.parseInt(stringTokenizer.nextElement().toString()); Double price = Double.parseDouble(stringTokenizer.nextElement().toString()); String username = stringTokenizer.nextElement().toString(); StringBuilder sb = new StringBuilder(); sb.append("\nId : " + id); sb.append("\nPrice : " + price); sb.append("\nUsername : " + username); sb.append("\n*******************\n"); System.out.println(sb.toString()); } } System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
出力
1| 3.29| example Id : 1 Price : 3.29 Username : example ******************* 2| 4.345| eclipse Id : 2 Price : 4.345 Username : eclipse ******************* Done