Guava File操作

Java的基本API对文件的操作很繁琐,为了向文件中写入一行文本,都需要写十几行的代码。guava对此作了很多改进,提供了很多方便的操作。

一. 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> TreadLines(File file, Charset charset, LineProcessor<T> callback)

Streams lines from a File, stopping when our callback returns false, or we have read all of the lines.

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类中还提供了其他一些文件的简捷方法。比如

  1. touch方法创建或者更新文件的时间戳。

  2. createTempDir()方法创建临时目录

  3. Files.createParentDirs(File) 创建父级目录

  4. getChecksum(File)获得文件的checksum

  5. hash(File)获得文件的hash

  6. map系列方法获得文件的内存映射

  7. getFileExtension(String)获得文件的扩展名

  8. getNameWithoutExtension(String file)获得不带扩展名的文件名

Guava的方法都提供了一些重载,这些重载可以扩展基本用法,我们也有必要去多了解一下,这些重载的方法。


附上Files类的doc:

static voidappend(CharSequence from, File to, Charset charset)

Appends a character sequence (such as a string) to a file using the given character set.

static ByteSinkasByteSink(File file, FileWriteMode... modes)

Returns a new ByteSink for writing bytes to the given file.

static ByteSourceasByteSource(File file)

Returns a new ByteSource for reading bytes from the given file.

static CharSinkasCharSink(File file, Charset charset, FileWriteMode... modes)

Returns a new CharSink for writing character data to the given file using the given character set.

static CharSourceasCharSource(File file, Charset charset)

Returns a new CharSource for reading character data from the given file using the given character set.

static voidcopy(File from, Charset charset, Appendable to)

Copies all characters from a file to an appendable object, using the given character set.

static voidcopy(File from, File to)

Copies all the bytes from one file to another.

static voidcopy(File from, OutputStream to)

Copies all bytes from a file to an output stream.

static voidcreateParentDirs(File file)

Creates any necessary but nonexistent parent directories of the specified file.

static FilecreateTempDir()

Atomically creates a new directory somewhere beneath the system's temporary directory (as defined by the java.io.tmpdirsystem property), and returns its name.

static booleanequal(File file1, File file2)

Returns true if the files contains the same bytes.

static TreeTraverser<File>fileTreeTraverser()

Returns a TreeTraverser instance for File trees.

static StringgetFileExtension(String fullName)

Returns the file extension for the given file name, or the empty string if the file has no extension.

static StringgetNameWithoutExtension(String file)

Returns the file name without its file extension or path.

static HashCodehash(File file, HashFunction hashFunction)

Computes the hash code of the file using hashFunction.

static Predicate<File>isDirectory()

Returns a predicate that returns the result of File.isDirectory() on input files.

static Predicate<File>isFile()

Returns a predicate that returns the result of File.isFile() on input files.

static MappedByteBuffermap(File file)

Fully maps a file read-only in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long).

static MappedByteBuffermap(File file, FileChannel.MapMode mode)

Fully maps a file in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long)using the requested FileChannel.MapMode.

static MappedByteBuffermap(File file, FileChannel.MapMode mode, long size)

Maps a file in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long) using the requested FileChannel.MapMode.

static voidmove(File from, File to)

Moves a file from one path to another.

static BufferedReadernewReader(File file, Charset charset)

Returns a buffered reader that reads from a file using the given character set.

static BufferedWriternewWriter(File file, Charset charset)

Returns a buffered writer that writes to a file using the given character set.

static <T> TreadBytes(File file, ByteProcessor<T> processor)

Process the bytes of a file.

static StringreadFirstLine(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> TreadLines(File file, Charset charset, LineProcessor<T> callback)

Streams lines from a File, stopping when our callback returns false, or we have read all of the lines.

static StringsimplifyPath(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 StringtoString(File file, Charset charset)

Reads all characters from a file into a String, using the given character set.

static voidtouch(File file)

Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name.

static voidwrite(byte[] from, File to)

Overwrites a file with the contents of a byte array.

static voidwrite(CharSequence from, File to, Charset charset)

Writes a character sequence (such as a string) to a file using the given character set.


转载于:https://my.oschina.net/stefanzhlg/blog/471251

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值