标签:
Java的基本API对文件的操作很繁琐,为了向文件中写入一行文本,都需要写十几行的代码。guava对此作了很多改进,提供了很多方便的操作。
Guava的Files类中提供了几个write方法来简化向文件中写入内容的操作,下面的例子演示 Files.write(byte[],File)的用法。
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Created by zhaoliangang on 15/6/26.
*/
public class GuavaFile {
public static void demoFileWrite(final String fileName, final String contents) {
checkNotNull(fileName, "Provided file name for writing must not be null.");
checkNotNull(contents, "Unable to write null contents.");
final File newFile = new File(fileName);
try {
Files.write(contents.getBytes(), newFile);
} catch (IOException fileIoEx) {
System.out.println("ERROR trying to write to file ‘" + fileName + "‘ - "
+ fileIoEx.toString());
}
}
public static void main(String[] args) {
GuavaFile.demoFileWrite("/Users/zhaoliangang/Documents/work/test.txt", "hello stefanie zhao");
}
}
Files类提供了readLines方法可以方便的读取文件的内容,如下demo代码:
public static void demoFileRead(final String filePath) throws IOException {
File testFile = new File(filePath);
List<String> lines = Files.readLines(testFile, Charsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
}
但是这个readLime方法是一次性读数据到内存,大文件当然就出现内存溢出了。
我们是用guava提供的另外一种readLine方法:
static <T> T |
readLines(File file, Charset charset, LineProcessor<T> callback)Streams lines from a |
public static void demoFileReadAsyn(final String filePath) throws IOException {
File testFile = new File(filePath);
Integer rowNum = Files.readLines(testFile, Charsets.UTF_16, new LineProcessor<Integer>() {
private int rowNum = 0;
public boolean processLine(String s) throws IOException {
rowNum ++;
return true;
}
public Integer getResult() {
return rowNum;
}
});
System.out.println(rowNum);
}
这个readLines的重载,需要我们实现一个LineProcessor的泛型接口,在这个接口的实现方法processLine方法中我们可以对行文本进行处理,getResult方法可以获得一个最终的处理结果,这里我们只是简单的返回了一个行计数。
另外还有readBytes方法可以对文件的字节做处理,readFirstLine可以返回第一行的文本,Files.toString(File,Charset)可以返回文件的所有文本内容。
final File sourceFile = new File(sourceFileName); final File targetFile = new File(targetFileName); Files.copy(sourceFile, targetFile);
Files.equal(file1, file2)
Guava的Files类中还提供了其他一些文件的简捷方法。比如
touch方法创建或者更新文件的时间戳。
createTempDir()方法创建临时目录
Files.createParentDirs(File) 创建父级目录
getChecksum(File)获得文件的checksum
hash(File)获得文件的hash
map系列方法获得文件的内存映射
getFileExtension(String)获得文件的扩展名
getNameWithoutExtension(String file)获得不带扩展名的文件名
Guava的方法都提供了一些重载,这些重载可以扩展基本用法,我们也有必要去多了解一下,这些重载的方法。
附上Files类的doc:
static void |
append(CharSequence from, File to, Charset charset)Appends a character sequence (such as a string) to a file using the given character set. |
static ByteSink |
asByteSink(File file, FileWriteMode... modes)Returns a new |
static ByteSource |
asByteSource(File file)Returns a new |
static CharSink |
asCharSink(File file, Charset charset, FileWriteMode... modes)Returns a new |
static CharSource |
asCharSource(File file, Charset charset)Returns a new |
static void |
copy(File from, Charset charset, Appendable to)Copies all characters from a file to an appendable object, using the given character set. |
static void |
copy(File from, File to)Copies all the bytes from one file to another. |
static void |
copy(File from, OutputStream to)Copies all bytes from a file to an output stream. |
static void |
createParentDirs(File file)Creates any necessary but nonexistent parent directories of the specified file. |
static File |
createTempDir()Atomically creates a new directory somewhere beneath the system‘s temporary directory (as defined by the |
static boolean |
equal(File file1, File file2)Returns true if the files contains the same bytes. |
static TreeTraverser<File> |
fileTreeTraverser()Returns a |
static String |
getFileExtension(String fullName)Returns the file extension for the given file name, or the empty string if the file has no extension. |
static String |
getNameWithoutExtension(String file)Returns the file name without its file extension or path. |
static HashCode |
hash(File file, HashFunction hashFunction)Computes the hash code of the |
static Predicate<File> |
isDirectory()Returns a predicate that returns the result of |
static Predicate<File> |
isFile()Returns a predicate that returns the result of |
static MappedByteBuffer |
map(File file)Fully maps a file read-only in to memory as per |
static MappedByteBuffer |
map(File file, FileChannel.MapMode mode)Fully maps a file in to memory as per |
static MappedByteBuffer |
map(File file, FileChannel.MapMode mode, long size)Maps a file in to memory as per |
static void |
move(File from, File to)Moves a file from one path to another. |
static BufferedReader |
newReader(File file, Charset charset)Returns a buffered reader that reads from a file using the given character set. |
static BufferedWriter |
newWriter(File file, Charset charset)Returns a buffered writer that writes to a file using the given character set. |
static <T> T |
readBytes(File file, ByteProcessor<T> processor)Process the bytes of a file. |
static String |
readFirstLine(File file, Charset charset)Reads the first line from a file. |
static List<String> |
readLines(File file, Charset charset)Reads all of the lines from a file. |
static <T> T |
readLines(File file, Charset charset, LineProcessor<T> callback)Streams lines from a |
static String |
simplifyPath(String pathname)Returns the lexically cleaned form of the path name, usually (but not always) equivalent to the original. |
static byte[] |
toByteArray(File file)Reads all bytes from a file into a byte array. |
static String |
toString(File file, Charset charset)Reads all characters from a file into a |
static void |
touch(File file)Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name. |
static void |
write(byte[] from, File to)Overwrites a file with the contents of a byte array. |
static void |
write(CharSequence from, File to, Charset charset)Writes a character sequence (such as a string) to a file using the given character set. |
标签:
原文地址:http://my.oschina.net/stefanzhlg/blog/471251