|
| 1 | +package com.mkyong.string; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.FileNotFoundException; |
| 5 | +import java.io.FileReader; |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.file.Files; |
| 8 | +import java.nio.file.Path; |
| 9 | +import java.nio.file.Paths; |
| 10 | +import java.util.ArrayList; |
| 11 | +import java.util.List; |
| 12 | +import java.util.StringTokenizer; |
| 13 | + |
| 14 | +public class StringTokenizerExample { |
| 15 | + |
| 16 | + public static void main(String[] args) throws IOException { |
| 17 | + |
| 18 | + StringTokenizer st = new StringTokenizer("1, 2, 3, 4, 5"); |
| 19 | + while (st.hasMoreTokens()) { |
| 20 | + System.out.println(st.nextToken().trim()); |
| 21 | + } |
| 22 | + |
| 23 | + /*String line = "This is a String, split by, StringTokenizer example."; |
| 24 | + List<String> result = split(line, ","); |
| 25 | + for (String s : result) { |
| 26 | + System.out.println(s.trim()); |
| 27 | + }*/ |
| 28 | + |
| 29 | + /*StringTokenizerExample obj = new StringTokenizerExample(); |
| 30 | + List<Trend> trends = obj.readFile(Paths.get("C:\\test\\sample.csv"), "|"); |
| 31 | + trends.forEach(System.out::println);*/ |
| 32 | + } |
| 33 | + |
| 34 | + public static List<String> split(String line, String delimiter) { |
| 35 | + List<String> result = new ArrayList<>(); |
| 36 | + StringTokenizer st = new StringTokenizer(line, delimiter); |
| 37 | + while (st.hasMoreTokens()) { |
| 38 | + result.add(st.nextToken()); |
| 39 | + } |
| 40 | + return result; |
| 41 | + } |
| 42 | + |
| 43 | + public List<Trend> readFile(Path path, String delimiter) throws IOException { |
| 44 | + |
| 45 | + List<Trend> result = new ArrayList<>(); |
| 46 | + |
| 47 | + try (BufferedReader br = new BufferedReader(new FileReader(path.toString()))) { |
| 48 | + |
| 49 | + String line; |
| 50 | + while ((line = br.readLine()) != null) { |
| 51 | + StringTokenizer st = new StringTokenizer(line, delimiter); |
| 52 | + while (st.hasMoreTokens()) { |
| 53 | + Integer id = Integer.parseInt(st.nextToken().trim()); |
| 54 | + Double index = Double.parseDouble(st.nextToken().trim()); |
| 55 | + String desc = st.nextToken().trim(); |
| 56 | + result.add(new Trend(id, index, desc)); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + class Trend { |
| 64 | + private int id; |
| 65 | + private Double index; |
| 66 | + private String desc; |
| 67 | + |
| 68 | + public Trend(int id, Double index, String desc) { |
| 69 | + this.id = id; |
| 70 | + this.index = index; |
| 71 | + this.desc = desc; |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + public String toString() { |
| 76 | + return "Trend{" + |
| 77 | + "id=" + id + |
| 78 | + ", index=" + index + |
| 79 | + ", desc='" + desc + '\'' + |
| 80 | + '}'; |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments