A 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 path1 = Paths.get("C:/", "Xmp");

Path path2 = Paths.get("C:/Xmp");

Path path3 = Paths.get(URI.create("file:///C:/Xmp/dd"));

2)FileSystems构造:

Path path4 = 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 perms = PosixFilePermissions.fromString("rw-rw-rw-");

//FileAttribute> 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 = 1at 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 stream =Files.newDirectoryStream(dir)){

for(Path e : stream){

System.out.println(e.getFileName());

}

}catch(IOException e){

}

try (Stream stream = Files.list(Paths.get("C:/"))){

Iterator 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) throwsIOException{

Path startingDir = Paths.get("C:\\apache-tomcat-8.0.21");

List result = new LinkedList();

Files.walkFileTree(startingDir, newFindJavaVisitor(result));

System.out.println("result.size()=" +result.size());

}

private static class FindJavaVisitor extends SimpleFileVisitor{

private Listresult;

public FindJavaVisitor(Listresult){

this.result =result;

}

@Override

publicFileVisitResult visitFile(Path file, BasicFileAttributes attrs){

if(file.toString().endsWith(".java")){

result.add(file.getFileName());

}

returnFileVisitResult.CONTINUE;

}

}

来一个实际例子:

public static void main(String[] args) throwsIOException {

Path startingDir = Paths.get("F:\\upload\\images"); //F:\\upload\\images\\2\\20141206

List result = new LinkedList();

Files.walkFileTree(startingDir, newFindJavaVisitor(result));

System.out.println("result.size()=" +result.size());

System.out.println("done.");

}

private static class FindJavaVisitor extends SimpleFileVisitor{

private Listresult;

public FindJavaVisitor(Listresult){

this.result =result;

}

@Override

publicFileVisitResult 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());

} returnFileVisitResult.CONTINUE;

}

}

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

public static void main(String[] args) throwsIOException {

Path startingDir = Paths.get("F:\\111111\\upload\\images"); //F:\111111\\upload\\images\\2\\20141206

List result = new LinkedList();

Files.walkFileTree(startingDir, newFindJavaVisitor(result));

System.out.println("result.size()=" +result.size());

System.out.println("done.");

}

private static class FindJavaVisitor extends SimpleFileVisitor{

private Listresult;

public FindJavaVisitor(Listresult){

this.result =result;

}

@Override

publicFileVisitResult 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();

returnFileVisitResult.CONTINUE;

}

result.add(file.getFileName());

returnFileVisitResult.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 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 的文档。

一个实际例子:

importjava.io.BufferedReader;

importjava.io.BufferedWriter;

importjava.nio.charset.StandardCharsets;

importjava.nio.file.Files;

importjava.nio.file.Path;

importjava.nio.file.Paths;

public classStringTools {

public static voidmain(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 path file转换_Java-技术专区-Files类和Paths类的用法相关推荐

  1. java path类_基于java Files类和Paths类的用法(详解)

    Java7中文件IO发生了很大的变化,专门引入了很多新的类: import java.nio.file.DirectoryStream; import java.nio.file.FileSystem ...

  2. 【Java基础】Java7新特性—Files类,Path类,Paths类的用法

    文章目录 Java7新增文件IO类 一.Paths 1.创建Paths 二.Path 1.创建Path 1.1.创建Path的三种方式 2.Path常用方法 三.Files 1.判断方法: 2.删除方 ...

  3. java getfiles_Java基础教程——File类、Paths类、Files类

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

  4. java万能编码转换_java编码转换的详细过程

    常见的JAVA程序包括以下类别: *直接在console上运行的类(包括可视化界面的类) *JSP代码类(注:JSP是Servlets类的变型) *Servelets类 *EJB类 *其它不可以直接运 ...

  5. java版 pdf转换_java如何将pdf转换成image

    java如何将pdf转换成image 发布时间:2020-08-26 03:05:15 来源:脚本之家 阅读:86 作者:yiluoak_47 本文实例为大家分享了java将pdf转换image的具体 ...

  6. java中file路径_Java中的文件路径

    Java中的文件路径 今天一定在这里解决这个问题,通过路径读文件一般就3种方式,但他们完全不同: 1. File myFile=new File("myfile.txt"); 上面 ...

  7. java程序日期转换_Java 日期转换详解及实例代码

    Java 日期转换 涉及的核心类:Date类.SimpleDateFormat类.Calendar类 一. Date型与long型 Date型转换为long型 Date date = new Date ...

  8. java 子类 父类 转换_Java子类与父类之间的类型转换

    1.向上转换 父类的引用变量指向子类变量时,子类对象向父类对象向上转换.从子类向父类的转换不需要什么限制,只需直接蒋子类实例赋值给父类变量即可,这也是Java中多态的实现机制. 2.向下转换 在父类变 ...

  9. java时间格式转换_Java时间日期格式转换

    突然忘记了时间格式怎么转换,特此做个记录 Java时间格式转换大全 import java.text.*; import java.util.Calendar; public class VeDate ...

最新文章

  1. 【转】QString 与中文问题
  2. flink window实例分析
  3. java基础知识点_JAVA基础知识
  4. c语言uint8的数组怎么转换为uint32_剖析JS和Redis的数据结构设计:数组
  5. 《Web Hacking 101》中的链接整理
  6. 《学习opencv》笔记——关于一些画图的函数
  7. 程序包androidx.support.annotation不存在/import androidx.v7.app.AppCompatActivity;报错
  8. 21款数据恢复软件,包含电脑PC、手机安卓、与苹果IOS免费下载
  9. html制作网页文字颜色代码,html网页设计教程关于html字体颜色设置方法是什么?...
  10. halcon 相似度_怎样用深度学习判断两张图片的相似度?
  11. 浦发银行面试笔试经历
  12. win10计算机未连接到网络适配器,Windows 10 Hyper-V网络适配器未连接
  13. 学习FPGA之四:FPGA开发方法
  14. SCHTASKS windows计划任务
  15. 201809-2买菜
  16. 袋式过滤器 - - 过滤与分离的基本原理,结构和布局的控制袋式过滤器
  17. ALC5621声卡调试记录
  18. ogg高版本到低版本同步
  19. a标签跳转新页面的各种方式
  20. 基于STC89C52单片机的智能家居系统

热门文章

  1. WRAP验厂辅导,WRAP验厂时会涉及到哪些法律法规
  2. 使用jqprint插件实现打印页面内容
  3. 《天道》一个人可能走得更快,但是一群人走得更远
  4. Android 监听开机广播实现应用开机自启动
  5. 眼图观测实验报告_眼图实验报告.docx
  6. 可怕的社会工程学黑客渗透技术,比骗术更高明的艺术
  7. Python搭建代理IP池(三)- 检测 IP
  8. 使用九宫格的方式加载动态加载资源
  9. mysql Truncated incorrect DOUBLE value解决办法
  10. [IMX6DL]fastboot erase SD分区实现