Guava: I/O utilities
java guava    2018-09-01 00:02:24    0    0    0
cqc   java guava
ByteStreams and CharStreams
ByteStreams处理的是字节, 对应的是InputStreamOutputStream CharStreams处理的是字符, 对应的是ReaderWriter注意:Guava提供的流操作方法都不需要用户去close流
ByteStreams
CharStreams
byte[] toByteArray(InputStream)
String toString(Readable)
N/A
List<String> readLines(Readable)
long copy(InputStream, OutputStream)
long copy(Readable, Appendable)
void readFully(InputStream, byte[])
N/A
void skipFully(InputStream, long)
void skipFully(Reader, long)
OutputStream nullOutputStream()
Writer nullWriter()

Sources and sinks

Guava为操作专门抽象出Source的概念,将不同的数据载体(如,File、URL)抽象成统一的操作方法,同样为操作专门抽象出Sink的概念
Creating sources and sinks
Bytes
Chars
Files.asByteSource(File)
Files.asCharSource(File, Charset)
Files.asByteSink(File, FileWriteMode...)
Files.asCharSink(File, Charset, FileWriteMode...)
Resources.asByteSource(URL)
Resources.asCharSource(URL, Charset)
ByteSource.wrap(byte[])
CharSource.wrap(CharSequence)
ByteSource.concat(ByteSource...)
CharSource.concat(CharSource...)
ByteSource.slice(long, long)
N/A
N/A
ByteSource.asCharSource(Charset)
N/A
ByteSink.asCharSink(Charset)
Source operations
ByteSource
CharSource
byte[] read()
String read()
N/A
ImmutableList<String> readLines()
N/A
String readFirstLine()
long copyTo(ByteSink)
long copyTo(CharSink)
long copyTo(OutputStream)
long copyTo(Appendable)
long size()
long length()
boolean isEmpty()
boolean isEmpty()
boolean contentEquals(ByteSource)
N/A
HashCode hash(HashFunction)
N/A
Sink operations
ByteSink
CharSink
void write(byte[])
void write(CharSequence)
long writeFrom(InputStream)
long writeFrom(Readable)
N/A
void writeLines(Iterable<? extends CharSequence>)
N/A
void writeLines(Iterable<? extends CharSequence>, String)
// Read the lines of a UTF-8 text file
ImmutableList<String> lines = Files.asCharSource(file, Charsets.UTF_8)
.readLines();

// Count distinct word occurrences in a file
Multiset<String> wordOccurrences = HashMultiset.create(
Splitter.on(CharMatcher.WHITESPACE)
.trimResults()
.omitEmptyStrings()
.split(Files.asCharSource(file, Charsets.UTF_8).read()));

// SHA-1 a file
HashCode hash = Files.asByteSource(file).hash(Hashing.sha1());

// Copy the data from a URL to a file
Resources.asByteSource(url).copyTo(Files.asByteSink(file));

Files

Guava也提供了一个和JDK7上的类似Files工具类,但我看Guava提供的功能似乎更丰富些,以下为官方提供的几个方法
Method
Description
createParentDirs(File)
Creates necessary but nonexistent parent directories of the file.
getFileExtension(String)
Gets the file extension of the file described by the path.
getNameWithoutExtension(String)
Gets the name of the file with its extension removed
simplifyPath(String)
Cleans up the path. Not always consistent with your filesystem; test carefully!
fileTreeTraverser()
Returns a TreeTraverser that can traverse file trees

上一篇: Guava:Multiset 允许添加重复元素的SET

下一篇: Guava:Multimap 一个key映射多个值

文档导航