java path类_基于java Files类和Paths类的用法(详解)
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的
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 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 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 = 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 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) throws IOException{
Path startingDir = Paths.get("C:\\apache-tomcat-8.0.21");
List result = new LinkedList();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
}
private static class FindJavaVisitor extends SimpleFileVisitor{
private List result;
public FindJavaVisitor(List 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 result = new LinkedList();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
System.out.println("done.");
}
private static class FindJavaVisitor extends SimpleFileVisitor{
private List result;
public FindJavaVisitor(List 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 result = new LinkedList();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
System.out.println("done.");
}
private static class FindJavaVisitor extends SimpleFileVisitor{
private List result;
public FindJavaVisitor(List 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 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类的用法(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
java path类_基于java Files类和Paths类的用法(详解)相关推荐
- vuecli 编译后部署_基于vue-cli 打包时抽离项目相关配置文件详解
前言:当使用vue-cli进行开发时时常需要动态配置一些设置,比如接口的请求地址(axios.defaults.baseURL),这些设置可能需要在项目编译后再进行设置的,所以在vue-cli里我们需 ...
- python画二维数组散点图_基于python二维数组及画图的实例详解
基于python二维数组及画图的实例详解 下面小编就为大家分享一篇基于python 二维数组及画图的实例详解,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 1.二维数组取值 注:不管 ...
- java订单类_基于Java创建一个订单类代码实例
这篇文章主要介绍了基于Java创建一个订单类代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 需求描述 定义一个类,描述订单信息 订单id 订 ...
- java刘备猜拳游戏类_基于java实现人机猜拳游戏
本文实例为大家分享了java实现人机猜拳游戏的具体代码,供大家参考,具体内容如下 完成人机猜拳互动游戏的开发,用户通过控制台输入实现出拳,电脑通过程序中的随机数实现出拳,每一局结束后都要输出结果.当用 ...
- java zip追加_基于Java向zip压缩包追加文件
这篇文章主要介绍了基于Java向zip压缩包追加文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 有个需求,从某个接口下载的一个zip压缩包,往里 ...
- dom4j工具类_基于DOM4J的XML文件解析类
XML文件解析分四类方式:DOM解析:SAX解析:JDOM解析:DOM4J解析.其中前两种属于基础方法,是官方提供的平台无关的解析方式:后两种属于扩展方法,它们是在基础的方法上扩展出来的,只适用于ja ...
- java web 编辑器_基于Java+web的在线Java编辑器 PDF 下载
主要内容: 近些年,互联网技术飞速发展,越来 越多的人接触到了编程语言,同时更多的 人愿意去了解学习编程语言,但由于以往 的编程语言编译器安装复杂,且部分还需 要配置环境,所以一些想学习编程语言的 人 ...
- java消费者模式_基于Java 生产者消费者模式(详细分析)
生产者消费者模式是多线程中最为常见的模式:生产者线程(一个或多个)生成面包放进篮子里(集合或数组),同时,消费者线程(一个或多个)从篮子里(集合或数组)取出面包消耗.虽然它们任务不同,但处理的资源是相 ...
- java ecc 加密_基于java实现的ECC加密算法示例
本文实例讲述了基于java实现的ECC加密算法.分享给大家供大家参考,具体如下: ECC ECC-Elliptic Curves Cryptography,椭圆曲线密码编码学,是目前已知的公钥体制中, ...
最新文章
- mac 下 mamp 配置虚拟主机步骤
- option 82与DHCP中继代理
- DrawerLayoutDemo【侧边栏(侧滑菜单)简单实现】
- mysql isam参数优化_MySQL MyISAM优化设置点滴
- [原创]RCP项目:数字图像处理软件
- 从动力学角度看优化算法:一个更整体的视角
- SQL常用语句大全(值得收藏)
- 【牛客161 - A】字符串(尺取法,桶标记法)
- 用matlab录制声音然后进行读取和播放
- VS、C#配置R语言开发环境
- 数据解读 | 高考志愿慎重填,大学四年不留白
- “确定“和“取消“摆放顺序
- 最小二乘法的原理讲解
- 下载chrome插件,离线安装chrome插件
- 【小程序开发】—— 封装自定义弹窗组件
- 【前端探索】移动端H5生成截图海报的探索
- 【附源码】计算机毕业设计Python安卓基于安卓的校园跑腿代购476ww(源码+程序+LW+调试部署)
- 数据结构之排序 --- 插入排序
- magicbookpro做php开发,荣耀MagicBook Pro测评:全面屏专业生产力工具
- 2018 大数据面试
热门文章
- java mysql 项目_mysql数据库如何实现与Java项目连接
- FileInputStream(文件字节输入流)
- 80V转15V,80V转12V,80V转5V的高压降压芯片
- 计算机化自适应测验 英语,情绪调节的计算机化自适应测验开发:CAT-ER
- 如果解除计算机密码,如何强制解除电脑开机密码win7教程
- Docker笔记(一)之概述
- C++小病毒(通用加强版)
- oracle行转列逗号分隔,Oracle逗号分隔列转行实现方法
- 用CSS伪类选择器做一个爱心
- 大米地理标志产品该如何宣传形象提升品牌知名度 看看五常大米是怎么做的