Guava 杂项笔记

这里主要记录Guava提供的一些工具类的用法。

Strings

空和null相互转换:

1
2
3
4
String s1 = Strings.emptyToNull("");
System.out.println(s1); // null
String s2 = Strings.nullToEmpty(null);
System.out.println(s2); //

获取相同的前缀和后缀:

1
2
3
4
String s3 = Strings.commonPrefix("mrbird", "mr.right");
System.out.println(s3); // mr
String s4 = Strings.commonSuffix("mrbird", "third");
System.out.println(s4); // ird

repeat重复操作:

1
2
String s5 = Strings.repeat("mrbird", 3);
System.out.println(s5); // mrbirdmrbirdmrbird

判断字符串是否为空或null:

1
2
boolean nullOrEmpty = Strings.isNullOrEmpty(null);
System.out.println(nullOrEmpty); // true

左侧填充和右侧填充:

1
2
3
4
String s6 = Strings.padStart("01", 5, '0');
System.out.println(s6); // 00001
String s7 = Strings.padEnd("1.0", 5, '0');
System.out.println(s7); // 1.000

StopWatcher

StopWatcher用于监测一段程序的执行耗时。我们之前通常的做法是:

1
2
3
4
System.out.println("程序开始处理");
long start = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(2);
System.out.println("程序处理结束,耗时" + (System.currentTimeMillis() - start) + "毫秒"); // 程序处理结束,耗时2.002 s

使用StopWatcher方便之处在于它会帮我们选取合适的时间单位:

1
2
3
4
System.out.println("程序开始处理");
Stopwatch stopwatch = Stopwatch.createStarted();
TimeUnit.SECONDS.sleep(2);
System.out.println("程序处理结束,耗时" + stopwatch.stop()); // 程序处理结束,耗时2.002 s

Preconditions断言

断言常用于类库设计中方法参数的判断,当参数不符合要求时,让程序提前抛异常结束。Preconditions是Guava提供的断言类。

非空校验

判断是否为空,为空的话抛出NullPointerException

1
2
List<String> list = null;
Preconditions.checkNotNull(list);

QQ截图20190505140513.png

自定义描述:

1
2
List<String> list = null;
Preconditions.checkNotNull(list, "list不能为空");

QQ截图20190505140642.png

自定义描述 + 长度校验:

1
2
List<String> list = null;
Preconditions.checkNotNull(list, "list长度必须为%s", 2);

QQ截图20190505140741.png

参数校验

校验不通过时,抛出IllegalArgumentException

1
2
String value = "hello";
Preconditions.checkArgument("world".equals(value), "参数内容必须为world");

QQ截图20190505140953.png

状态校验

校验不通过时,抛出IllegalStateException

1
2
String state = "on";
Preconditions.checkState("off".equals(state), "状态必须为off");

QQ截图20190505141058.png

校验元素个数

校验不通过,抛出IndexOutOfBoundsException

1
2
List<String> list = ImmutableList.of();
Preconditions.checkElementIndex(10, list.size(), "下标越界,不存在第10个元素");

QQ截图20190505141210.png

IO操作

演示之前先创建一个source.txt文件:

1
2
Guava I/O operation
Guava I/O 操作

相关常量:

1
2
private static final String SOURCE_FILE = "C:\\Users\\Administrator\\Desktop\\guavatest\\src\\test\\java\\cc\\mrbird\\resources\\source.txt";
private static final String TARGET_FILE = "C:\\Users\\Administrator\\Desktop\\guavatest\\src\\test\\java\\cc\\mrbird\\resources\\target.txt";

文件拷贝

1
2
3
File targetFile = new File(TARGET_FILE);
Files.copy(new File(SOURCE_FILE), targetFile);
System.out.println(targetFile.exists()); // true

QQ截图20190505141800.png

文件移动

1
Files.move(new File(SOURCE_FILE), new File(TARGET_FILE));

文件移动和文件拷贝的区别是,文件移动会删除源文件:

QQ截图20190505142008.png

读取文件内容

将文件内容读取到String集合中:

1
2
List<String> list = Files.readLines(new File(SOURCE_FILE), Charsets.UTF_8);
list.forEach(System.out::println);

QQ截图20190505142229.png

读的过程中进行一些加工:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
LineProcessor<List<String>> lineProcessor = new LineProcessor<List<String>>() {
List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
if (line.length() != 0) {
result.add(line + "。");
}
return true;
}
@Override
public List<String> getResult() {
return result;
}
};
List<String> result = Files.asCharSource(new File(SOURCE_FILE), Charsets.UTF_8).readLines(lineProcessor);
System.out.println(result); // [Guava I/O operation。, Guava I/O 操作。]

写操作

追加操作:

1
2
3
4
5
6
7
File file = new File(SOURCE_FILE);
String value = "添加一些内容";
CharSink charSink = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); // 追加
charSink.write(value);

String read = Files.asCharSource(file, Charsets.UTF_8).read();
System.out.println(read);

QQ截图20190505142616.png

覆盖操作:

1
2
3
4
5
6
7
File file = new File(SOURCE_FILE);
String value = "添加一些内容";
CharSink charSink = Files.asCharSink(file, Charsets.UTF_8); // 覆盖
charSink.write(value);

String read = Files.asCharSource(file, Charsets.UTF_8).read();
System.out.println(read);

QQ截图20190505142740.png

文件转为哈希码

1
2
3
File file = new File(SOURCE_FILE);
HashCode hash = Files.asByteSource(file).hash(Hashing.sha256());
System.out.println(hash); // c46982603d4b2ba5032d73dc1fffbe1aea1f11d75921b2839632c56636673d31

文件创建

1
2
3
4
5
String TOUCH_FILE = "C:\\Users\\Administrator\\Desktop\\guavatest\\src\\test\\java\\cc\\mrbird\\resources\\new.txt";
File file = new File(TOUCH_FILE);
Files.touch(file);
boolean exists = file.exists();
System.out.println(exists); // true

递归操作

由浅入深:

1
2
3
4
5
6
7
8
9
10
File file = new File("C:\\Users\\Administrator\\Desktop\\guavatest\\src\\test\\java\\cc\\mrbird");
// depthFirstPreOrder 由浅入深
Iterable<File> files = Files.fileTraverser().depthFirstPreOrder(file);
files.forEach(f -> {
if (f.isDirectory()) {
System.out.println("directory: " + f);
} else {
System.out.println("file: " + f);
}
});

QQ截图20190505143344.png

由深入浅:

1
2
3
4
5
6
7
8
9
10
File file = new File("C:\\Users\\Administrator\\Desktop\\guavatest\\src\\test\\java\\cc\\mrbird");
// depthFirstPostOrder 由深入浅
Iterable<File> files = Files.fileTraverser().depthFirstPostOrder(file);
files.forEach(f -> {
if (f.isDirectory()) {
System.out.println("directory: " + f);
} else {
System.out.println("file: " + f);
}
});

QQ截图20190505143508.png

请作者喝瓶肥宅水🥤

0