java7中新文件操作类Files

jdk7提供了新的文件操作类,在java.nio.file包下,同时也提供paths类,试用了一下,还是不错,代码和大家分享一下:

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesTest {
    public static void main(String[] args) throws Exception {
        //如果test不存在,创建目录
        if(Files.notExists(Paths.get("E:\\test"))){
            Files.createDirectories(Paths.get("E:\\test"));
        }

        if(Files.notExists(Paths.get("E:\\test\\a.txt"))){
            //创建a.txt文件
            Files.createFile(Paths.get("E:\\test\\a.txt"));
        }

        //返回bufferWriter可以直接写文件,利用try-with-source写法,会自动关闭连接
        //StandardCharsets.UTF_8 utf-8的编码
        try(BufferedWriter bw = Files.newBufferedWriter(Paths.get("E:\\test\\a.txt"), StandardCharsets.UTF_8)){
            bw.write("dksdkfkdks sdkfjksdjl ddd dksk dsdfsdf sdfsldfjewofsl dsdfsdfsdfesdf\n"
                    + "sdfs daaaaaaaaaa dfesdfkajfoafmoapfhq sladjfowqmfoqhf ddsdfsf");
            bw.flush();
        }

        //创建b.txt文件
        Files.createFile(Paths.get("E:\\test\\b.txt"));
        //返回流的方式,上面的例子返回的是BufferedWriter,StandardOpenOption.APPEND这个参数不传,是覆盖
        try(OutputStream os = Files.newOutputStream(Paths.get("E:\\test\\b.txt"),
                StandardOpenOption.APPEND)){
            os.write(("ddddd".getBytes()));
            os.close();
        }

        Files.deleteIfExists(Paths.get("E:\\test\\b.txt"));
        if(Files.exists(Paths.get("E:\\test\\a.txt"))){
            //可以用于修改名字,类似于linux的mv
            Files.move(Paths.get("E:\\test\\a.txt") ,Paths.get("E:\\test\\c.txt"));
            //移动文件
            Files.move(Paths.get("E:\\test\\c.txt") ,Paths.get("D:\\c.txt"));
        }

    }
}

 

猜你喜欢

转载自studypi.iteye.com/blog/2399605
今日推荐