1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| public class CommonUsage {
@Test public void collection2Srt() { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); String result = Joiner.on("-").join(list); System.out.println(result);
HashMap<String, Integer> map = Maps.newHashMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); String s = Joiner.on(",").withKeyValueSeparator("=").join(map); System.out.println(s); }
@Test public void str2Collection() { String s = "1,2,3,4,5,6,7,8,9"; List<String> list = Splitter.on(",").splitToList(s); System.out.println(list);
s = "1-2-3-4- 5- 6 "; List<String> list1 = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(s); System.out.println(list1);
String str = "a=1,b=2"; Map<String, String> map = Splitter.on(",").withKeyValueSeparator("=").split(str); }
@Test public void strSplit() { String input = "aa.dd,,ff,,."; List<String> list = Splitter.onPattern("[.|,]").omitEmptyStrings().trimResults() .splitToList(input); System.out.println(list); boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')) .matches('K'); String s1 = CharMatcher.digit().retainFrom("abc 123 efg"); String s2 = CharMatcher.digit().removeFrom("abc 123 efg"); }
@Test public void countTime() { Stopwatch stopwatch = Stopwatch.createStarted(); for (int i = 0; i < 100000; i++) { } long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS); System.out.println(nanos); }
@Test public void filesOperation() { String fileName = "./src/main/java/com/hisen/jars/guava/test.txt"; for (int i = 0; i < 1000; i++) { filesWrite(fileName, String.valueOf(i) + "\n"); } List<String> list = filesRead(fileName); System.out.println("读取到的内容:" + list.toString());
}
public void filesWrite(final String fileName, final String contents) { checkNotNull(fileName, "文件名称不能为空"); checkNotNull(contents, "写入内容不能为空"); final File file = new File(fileName); try { Files.append(contents, file, Charsets.UTF_8); } catch (IOException e) { System.out.println("ERROR trying to write to file '" + fileName + "' - " + e.toString()); } }
public List<String> filesRead(String filePath) { checkNotNull(filePath, "文件名称不能为空"); File file = new File(filePath); List<String> list = null; try { list = Files.readLines(file, Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return list; } }
|