guava文件操作

来源:互联网 发布:手机添加网络什么意思 编辑:程序博客网 时间:2024/06/02 07:18
guava对文件的基本读写操作
package com.panther.file;import com.google.common.base.Charsets;import com.google.common.io.Files;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.File;import java.util.List;import static com.google.common.base.Preconditions.*;/** * Guava的文件写入 * Guava的Files类中提供了几个write方法来简化向文件中写入内容的操作, * 下面的例子演示 Files.write(byte[],File)的用法。 * Created by panther.dongdong on 2015/11/15. */public class FileOperate {    private static final Logger LOGGER = LoggerFactory.getLogger(FileOperate.class.getName());    private final static String OUTPUT_FILE = "./src/main/resources/file/test";    public static void main(String[] args) {        LOGGER.info("写入文件之前");        demoFileWrite(OUTPUT_FILE, "这是写入的内容");        LOGGER.info("写入文件之后");        LOGGER.info("读文件之前");        demoFileRead(OUTPUT_FILE);        LOGGER.info("读文件之后");    }    /**     * guava将信息写入到文件中的方法     *     * @param fileName 文件名字     * @param contents 写入的内容     */    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 (Exception e) {            LOGGER.error("ERROR trying to write to file '" + fileName + "' - "                    + e.toString());        }    }    public static void demoFileRead(final String testFilePath) {        File testFile = new File(testFilePath);        List<String> lines = null;        try {            lines = Files.readLines(testFile, Charsets.UTF_8);        } catch (Exception e) {            LOGGER.error("读入文件出现异常:{}", e.getMessage());        }        for (String line : lines) {            LOGGER.info(line);        }    }}

大文件的特殊处理:

package com.panther.file;import com.google.common.base.Charsets;import com.google.common.io.Files;import com.google.common.io.LineProcessor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.File;import java.io.IOException;/** * 当读取的文件太大就不能直接放入内存中,这样会把内存充爆 * 出现OutofMemoryError * 大文件处理可以使用readLines方法的另一个重载。 * 下面的例子演示从一个大文件中逐行读取文本,并做行号计数。 * Created by panther.dongdong on 2015/11/15. */public class FileOperateSpecial {    private final static String INPUT_FILE = "./src/main/resources/file/read.txt";    private final static Logger LOGGER = LoggerFactory.getLogger(FileOperateSpecial.class.getName());    static class ReadLine implements LineProcessor<Integer> {        private Integer totalRow = 0;        @Override        public boolean processLine(String line) throws IOException {            LOGGER.info("文件的信息是:{}", line);            totalRow++;            return true;        }        @Override        public Integer getResult() {            return totalRow;        }    }    public static void main(String[] args) {        File testFile = new File(INPUT_FILE);        ReadLine counter = new ReadLine();        try {            Files.readLines(testFile, Charsets.UTF_8, counter);        } catch (Exception e) {            LOGGER.error("读取文件发生异常:{},异常信息:{}", e, e.getMessage());        }        LOGGER.info("文件的总行数:{}", counter.getResult());    }}/** * 总结: * 这个readLines的重载,需要我们实现一个LineProcessor的泛型接口, * 在这个接口的实现方法processLine方法中我们可以对行文本进行处理, * getResult方法可以获得一个最终的处理结果,这里我们只是简单的返回了一个行计数。 * 另外还有readBytes方法可以对文件的字节做处理, * readFirstLine可以返回第一行的文本, * Files.toString(File,Charset)可以返回文件的所有文本内容。 */

其他操作(ex:文件复制,移动,比较等)

package com.panther.file;import com.google.common.io.Files;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.File;import static com.google.common.base.Preconditions.checkNotNull;/** * guava文件的其他操作 * copy,move(复制,移动,剪切) * 在Guava中复制文件操作提供了一组的copy方法, * 示例如下: * Created by panther.dongdong on 2015/11/15. */public class FileOperateOther {    private static final Logger LOGGER = LoggerFactory.getLogger(FileOperateOther.class.getName());    private static final String SOURCE = "./src/main/resources/file/source";    private static final String TARGET = "./src/main/resources/file/target";    public static void main(String[] args) {        LOGGER.info("拷贝文件开始");        long start = System.currentTimeMillis();        FileOperateOther.demoFileCopy(SOURCE, TARGET);        long middle = System.currentTimeMillis();        LOGGER.info("拷贝文件结束,所花费时间:{}ms", (middle - start));        LOGGER.info("比较文件开始");        demoFileEqual(SOURCE, TARGET);        LOGGER.info("文件比较结束,耗时:{}", (System.currentTimeMillis() - start));    }    /**     * 演示如何使用guava的Files.copy方法复制文件     * Guava中移动文件使用move方法,用法和copy一样。     *     * @param sourceFileName 复制的源文件名     * @param targetFileName 目标文件名     */    public static void demoFileCopy(            final String sourceFileName, final String targetFileName) {        checkNotNull(sourceFileName, "Copy source file name must NOT be null.");        checkNotNull(targetFileName, "Copy target file name must NOT be null.");        final File sourceFile = new File(sourceFileName);        final File targetFile = new File(targetFileName);        try {            Files.copy(sourceFile, targetFile);        } catch (Exception e) {            LOGGER.error("复制文件出现异常:{},异常信息:{}", e, e.getMessage());        }    }    /**     * 演示 Files.equal(File,File) 来比较两个文件的内容     * Guava中提供了Files.equal(File,File)方法来比较两个文件的内容是否完全一致,请看下面的示     *     * @param fileName1 比较的文件1文件名     * @param fileName2 比较的文件2文件名     */    public static void demoFileEqual(final String fileName1, final String fileName2) {        checkNotNull(fileName1, "First file name for comparison must NOT be null.");        checkNotNull(fileName2, "Second file name for comparison must NOT be null.");        final File file1 = new File(fileName1);        final File file2 = new File(fileName2);        try {            LOGGER.info("两个文件的比较结果是:{}", Files.equal(file1, file2));        } catch (Exception e) {            LOGGER.error(                    "比较两个文件内容时候发生异常,文件1:{},文件2:{},异常信息为:{},异常为:{}", file1, file2, e.getMessage(), e);        }    }}/** * 补充: * Guava的Files类中还提供了其他一些文件的简捷方法。比如 * touch方法创建或者更新文件的时间戳。 * createTempDir()方法创建临时目录 * Files.createParentDirs(File) 创建父级目录 * getChecksum(File)获得文件的checksum * hash(File)获得文件的hash * map系列方法获得文件的内存映射 * getFileExtension(String)获得文件的扩展名 * getNameWithoutExtension(String file)获得不带扩展名的文件名 */


0 0
原创粉丝点击