http://blog.csdn.net/u010889616/article/details/52694061

Java7中文件IO发生了很大的变化,专门引入了很多新的类:

import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

......等等,来取代原来的基于java.io.File的文件IO操作方式.

1. Path就是取代File的

Path represents a path that is hierarchical and composed
of a sequence of directory and file name elements separated by a special
separator or delimiter.

Path用于来表示文件路径和文件。可以有多种方法来构造一个Path对象来表示一个文件路径,或者一个文件:

1)首先是final类Paths的两个static方法,如何从一个路径字符串来构造Path对象:

        Path path = Paths.get("C:/", "Xmp");
Path path2 = Paths.get("C:/Xmp"); URI u = URI.create("file:///C:/Xmp/dd");
Path p = Paths.get(u);

2)FileSystems构造:

Path path3 = FileSystems.getDefault().getPath("C:/", "access.log");

3)File和Path之间的转换,File和URI之间的转换:

        File file = new File("C:/my.ini");
Path p1 = file.toPath();
p1.toFile();
file.toURI();

4)创建一个文件:

        Path target2 = Paths.get("C:\\mystuff.txt");
// Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-rw-rw-");
// FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms);
try {
if(!Files.exists(target2))
Files.createFile(target2);
} catch (IOException e) {
e.printStackTrace();
}

windows下不支持PosixFilePermission来指定rwx权限。

5)Files.newBufferedReader读取文件:

        try {
// Charset.forName("GBK")
BufferedReader reader = Files.newBufferedReader(Paths.get("C:\\my.ini"), StandardCharsets.UTF_8);
String str = null;
while((str = reader.readLine()) != null){
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}

可以看到使用 Files.newBufferedReader 远比原来的FileInputStream,然后BufferedReader包装,等操作简单的多了。

这里如果指定的字符编码不对,可能会抛出异常 MalformedInputException ,或者读取到了乱码:

java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.coin.Test.main(Test.java:79)

6)文件写操作:

        try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get("C:\\my2.ini"), StandardCharsets.UTF_8);
writer.write("测试文件写操作");
writer.flush();
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}

7)遍历一个文件夹:

        Path dir = Paths.get("D:\\webworkspace");
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)){
for(Path e : stream){
System.out.println(e.getFileName());
}
}catch(IOException e){ }
        try (Stream<Path> stream = Files.list(Paths.get("C:/"))){
Iterator<Path> ite = stream.iterator();
while(ite.hasNext()){
Path pp = ite.next();
System.out.println(pp.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}

上面是遍历单个目录,它不会遍历整个目录。遍历整个目录需要使用:Files.walkFileTree

8)遍历整个文件目录:

    public static void main(String[] args) throws IOException{
Path startingDir = Paths.get("C:\\apache-tomcat-8.0.21");
List<Path> result = new LinkedList<Path>();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
} private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> result){
this.result = result;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
if(file.toString().endsWith(".java")){
result.add(file.getFileName());
}
return FileVisitResult.CONTINUE;
}
}

来一个实际例子:

    public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("F:\\upload\\images"); // F:\\upload\\images\\2\\20141206
List<Path> result = new LinkedList<Path>();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size()); System.out.println("done.");
} private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> result){
this.result = result;
} @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
String filePath = file.toFile().getAbsolutePath();
if(filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")){
try {
Files.deleteIfExists(file);
} catch (IOException e) {
e.printStackTrace();
}
result.add(file.getFileName());
} return FileVisitResult.CONTINUE;
}
}

将目录下面所有符合条件的图片删除掉:filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")

    public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("F:\\111111\\upload\\images"); // F:\111111\\upload\\images\\2\\20141206
List<Path> result = new LinkedList<Path>();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size()); System.out.println("done.");
} private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> result){
this.result = result;
} @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
String filePath = file.toFile().getAbsolutePath();
int width = 224;
int height = 300;
StringUtils.substringBeforeLast(filePath, ".");
String newPath = StringUtils.substringBeforeLast(filePath, ".") + "_1."
+ StringUtils.substringAfterLast(filePath, ".");
try {
ImageUtil.zoomImage(filePath, newPath, width, height);
} catch (IOException e) {
e.printStackTrace();
return FileVisitResult.CONTINUE;
}
result.add(file.getFileName());
return FileVisitResult.CONTINUE;
}
}

为目录下的所有图片生成指定大小的缩略图。a.jpg 则生成 a_1.jpg

2. 强大的java.nio.file.Files

1)创建目录和文件:

        try {
Files.createDirectories(Paths.get("C://TEST"));
if(!Files.exists(Paths.get("C://TEST")))
Files.createFile(Paths.get("C://TEST/test.txt"));
// Files.createDirectories(Paths.get("C://TEST/test2.txt"));
} catch (IOException e) {
e.printStackTrace();
}

注意创建目录和文件Files.createDirectories 和 Files.createFile不能混用,必须先有目录,才能在目录中创建文件。

2)文件复制:

从文件复制到文件:Files.copy(Path source, Path target, CopyOption options);

从输入流复制到文件:Files.copy(InputStream in, Path target, CopyOption options);

从文件复制到输出流:Files.copy(Path source, OutputStream out);

        try {
Files.createDirectories(Paths.get("C://TEST"));
if(!Files.exists(Paths.get("C://TEST")))
Files.createFile(Paths.get("C://TEST/test.txt"));
// Files.createDirectories(Paths.get("C://TEST/test2.txt"));
Files.copy(Paths.get("C://my.ini"), System.out);
Files.copy(Paths.get("C://my.ini"), Paths.get("C://my2.ini"), StandardCopyOption.REPLACE_EXISTING);
Files.copy(System.in, Paths.get("C://my3.ini"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}

3)遍历一个目录和文件夹上面已经介绍了:Files.newDirectoryStream , Files.walkFileTree

4)读取文件属性:

            Path zip = Paths.get(uri);
System.out.println(Files.getLastModifiedTime(zip));
System.out.println(Files.size(zip));
System.out.println(Files.isSymbolicLink(zip));
System.out.println(Files.isDirectory(zip));
System.out.println(Files.readAttributes(zip, "*"));

5)读取和设置文件权限:

            Path profile = Paths.get("/home/digdeep/.profile");
PosixFileAttributes attrs = Files.readAttributes(profile, PosixFileAttributes.class);// 读取文件的权限
Set<PosixFilePermission> posixPermissions = attrs.permissions();
posixPermissions.clear();
String owner = attrs.owner().getName();
String perms = PosixFilePermissions.toString(posixPermissions);
System.out.format("%s %s%n", owner, perms); posixPermissions.add(PosixFilePermission.OWNER_READ);
posixPermissions.add(PosixFilePermission.GROUP_READ);
posixPermissions.add(PosixFilePermission.OTHERS_READ);
posixPermissions.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(profile, posixPermissions); // 设置文件的权限

Files类简直强大的一塌糊涂,几乎所有文件和目录的相关属性,操作都有想要的api来支持。这里懒得再继续介绍了,详细参见 jdk8 的文档。

一个实际例子:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; public class StringTools {
public static void main(String[] args) {
try {
BufferedReader reader = Files.newBufferedReader(Paths.get("C:\\Members.sql"), StandardCharsets.UTF_8);
BufferedWriter writer = Files.newBufferedWriter(Paths.get("C:\\Members3.txt"), StandardCharsets.UTF_8); String str = null;
while ((str = reader.readLine()) != null) {
if (str != null && str.indexOf(", CAST(0x") != -1 && str.indexOf("AS DateTime)") != -1) {
String newStr = str.substring(0, str.indexOf(", CAST(0x")) + ")";
writer.write(newStr);
writer.newLine();
}
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

场景是,sql server导出数据时,会将 datatime 导成16进制的binary格式,形如:, CAST(0x0000A2A500FC2E4F AS DateTime))

所以上面的程序是将最后一个 datatime 字段导出的 , CAST(0x0000A2A500FC2E4F AS DateTime) 删除掉,生成新的不含有datetime字段值的sql 脚本。用来导入到mysql中。

做到半途,其实有更好的方法,使用sql yog可以很灵活的将sql server中的表以及数据导入到mysql中。使用sql server自带的导出数据的功能,反而不好处理。

java Files类和Paths类的用法 (转)的更多相关文章

  1. Java基础教程——File类、Paths类、Files类

    File类 File类在java.io包中.io代表input和output,输入和输出. 代表与平台无关的文件和目录. 可以新建.删除.重命名,但不能访问文件内容. File类里的常量: impor ...

  2. Java 中对象锁和类锁的区别? 关键字 Synchronized的用法?

    一  对象锁和类锁的关系 /* * 对象锁和[类锁] 全局锁的关系? 对象锁是用于对象实例方法,或者一个对象实例上的 this 类锁是用于类的静态方法或者一个类的class对象上的. Ag.class ...

  3. java中的 FileWriter类 和 FileReader类的一些基本用法

    1,FileWriter类(字符输出流类) |--用来写入字符文件的便捷类.此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的.要自己指定这些值,可以先在 FileOutputStream ...

  4. java时间类Date、Calendar及用法

    对于时间类,这篇主要说明各种现实情况下如何取值,怎么定向取值,得到自己想要的时间参数.在java中时间类主要有Date.Calendar,暂时只介绍 java.util.*下的时间类,对于java.s ...

  5. 【Java学习】Font字体类的用法介绍

    一.Font类简介 Font类是用于设置图形用户界面上的字体样式的,包括字体类型(例如宋体.仿宋.Times New Roman等).字体风格(例如斜体字.加粗等).以及字号大小. 二.Font类的引 ...

  6. Java学习 时间类 Period类与Duration类 / LocalDate类与Instant类 用法详解

    前言 java 8 中引入的两个与日期相关的新类:Period 和 Duration.两个类看表示时间量或两个日期之间的差,两者之间的差异为:Period基于日期值,而Duration基于时间值.他们 ...

  7. java.io 包下的类有哪些 + 面试题

    java.io 包下的类有哪些 + 面试题 IO 介绍 IO 是 Input/Output 的缩写,它是基于流模型实现的,比如操作文件时使用输入流和输出流来写入和读取文件等. IO 分类 传统的 IO ...

  8. Java高效编程之三【类和接口】

    本部分包含的一些指导原则,可以帮助哦我们更好滴利用这些语言元素,以便让设计出来的类更加有用.健壮和灵活. 十二.使类和成员的访问能力最小化 三个关键词访问修饰符:private(私有的=类级别的).未 ...

  9. java之io之file类的常用操作

    java io 中,file类是必须掌握的.它的常用api用法见实例. package com.westward.io; import java.io.File; import java.io.IOE ...

随机推荐

  1. python django day 4 database

    django-admin.py startproject learn_models # 新建一个项目 cd learn_models # 进入到该项目的文件夹 django-admin.py star ...

  2. hdu3488 Tour 拆点+二分图最佳匹配

    In the kingdom of Henryy, there are N (2 <= N <= 200) cities, with M (M <= 30000) one-way r ...

  3. 【spring源码分析】BeanDefinitionRegistryPostProcessor接口可自定义bean加入IOC

    自定义BeanDefinitionRegistryPostProcessor BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcesso ...

  4. Eclipse和Intel idea的常用技巧

    使用Eclipse的几个必须掌握的快捷方式   “工若善其事,必先利其器”,感谢Eclipse,她 使我们阅读一个大工程的代码更加容易,在阅读的过程中,我发现掌握几个Eclipse的快捷键会使阅读体验 ...

  5. centos 7 lvs 负载均衡搭建部署

    环境: 在vm里开三个虚拟机 负载调度器:10.0.3.102 真实服务器1:10.0.3.103 真实服务器2:10.0.3.104 虚拟ip: 10.0.3.99 (用来飘移) 负载调度器上 if ...

  6. Tower Defense Toolkit 学习

    代码太多,就不贴了.用到的基本已注释. 游戏中的数据存放在Resources/Database中.游戏运行时,通过Resources.Load加载 UI构成   对象池 using UnityEngi ...

  7. spring中ApplicationContextAware接口描述

    项目中使用了大量的工厂类,采用了简单工厂模式: 通过该工厂类可以获取指定的处理器bean,这些处理器bean我们是从spring容器中获取的,如何获取,是通过实现ApplicationContextA ...

  8. chmod修改权限

    1.命令简介 chmod(Change mode) 用来将每个文件的模式更改为指定值.Linux/Unix 的档案调用权限分为三级 : 档案拥有者.群组.其他. u :目录或者文件的当前的用户 g : ...

  9. 干货-递归下降分析器 笔记(具体看Python Cookbook, 3rd edition 的2.19章节)

    import re import collections # 写将要匹配的正则 NUM = r'(?P<NUM>\d+)' PLUS = r'(?P<PLUS>\+)' MIN ...

  10. ASP.NET AJAX入门系列(2):使用ScriptManager控件

    ScriptManager控件包括在ASP.NET 2.0 AJAX Extensions中,它用来处理页面上的所有组件以及页面局部更新,生成相关的客户端代理脚本以便能够在JavaScript中访问W ...