Guava入门第八章(Files)

package com.lvshihao.guava;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

public class FilesTest {

    private final String SOURCE_FILE="D:\IDEA_PROJECT\test\src\test\java\files\My.txt";
    private final String TARGET_FILE="D:\IDEA_PROJECT\test\src\test\java\files\Mye.txt";

    @Test
    public void testCopyFileWithGuava() throws IOException {
        Files.copy(new File(SOURCE_FILE),new File(TARGET_FILE));
        assertThat(new File(TARGET_FILE).isFile(),equalTo(true));
    }
    @Test
    public void testCopyFileWithJDKNio2() throws IOException {
        java.nio.file.Files.copy(
                Paths.get(SOURCE_FILE),
                Paths.get(TARGET_FILE),
                StandardCopyOption.COPY_ATTRIBUTES);
        assertThat(new File(TARGET_FILE).isFile(),equalTo(true));
    }

    @Test
    public void testMoveFile() throws IOException {
       try{
           Files.move(new File(SOURCE_FILE),new File(TARGET_FILE));
           assertThat(new File(SOURCE_FILE).exists(),equalTo(false));
           assertThat(new File(TARGET_FILE).exists(),equalTo(true));
       }finally {
           Files.move(new File(TARGET_FILE),new File(SOURCE_FILE));
       }
    }

   @Test
    public void testToString() throws IOException {
        final String expectedString ="lvshihao with guava hello html is ib+" +
                "please read the guava document or source code.+" +
                "the guava source code is very";
        List strings = Files.readLines(new File(SOURCE_FILE), Charsets.UTF_8);
        String result = Joiner.on("+").join(strings);
        assertThat(result,equalTo(expectedString));
    }
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

作者:吕世昊

个性签名:学习如逆水行舟,不进则退!

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

原文地址:https://www.cnblogs.com/lvshihao/p/15167650.html