原
java7 NIO2(4) 文件和目录操作API
2012年12月30日 16:24:16 阅读数:10431更多
个人分类: java
文件和目录操作API,跟原来FILE IO做了很多改进,我们看看新的API,这个也是NIO操作的基础。
-
package com.mime;
-
import java.io.BufferedReader;
-
import java.io.BufferedWriter;
-
import java.io.File;
-
import java.io.FileInputStream;
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.io.OutputStream;
-
import java.io.OutputStreamWriter;
-
import java.nio.charset.Charset;
-
import java.nio.file.DirectoryStream;
-
import java.nio.file.FileSystems;
-
import java.nio.file.Files;
-
import java.nio.file.LinkOption;
-
import java.nio.file.Path;
-
import java.nio.file.Paths;
-
import java.nio.file.StandardCopyOption;
-
import java.nio.file.StandardOpenOption;
-
import java.nio.file.attribute.FileAttribute;
-
import java.nio.file.attribute.PosixFilePermission;
-
import java.nio.file.attribute.PosixFilePermissions;
-
import java.util.List;
-
import java.util.Set;
-
public class NIO2FileAndDir {
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
Path path = FileSystems.getDefault().getPath(
-
System.getProperty("user.home"), "www", "pyweb.settings");
-
// 检查文件是否存在 exist, not exist, or unknown.
-
// !Files.exists(...) is not equivalent to Files.notExists(...) and the
-
// notExists() method is not a complement of the exists() method
-
// 如果应用没有权限访问这个文件,则两者都返回false
-
boolean path_exists = Files.exists(path,
-
new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
-
boolean path_notexists = Files.notExists(path,
-
new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
-
System.out.println(path_exists);
-
System.out.println(path_notexists);
-
// 检测文件访问权限
-
boolean is_readable = Files.isReadable(path);
-
boolean is_writable = Files.isWritable(path);
-
boolean is_executable = Files.isExecutable(path);
-
boolean is_regular = Files.isRegularFile(path,
-
LinkOption.NOFOLLOW_LINKS);
-
if ((is_readable) && (is_writable) && (is_executable) && (is_regular)) {
-
System.out.println("The checked file is accessible!");
-
} else {
-
System.out.println("The checked file is not accessible!");
-
}
-
// 检测文件是否指定同一个文件
-
Path path_1 = FileSystems.getDefault().getPath(
-
System.getProperty("user.home"), "www", "pyweb.settings");
-
Path path_2 = FileSystems.getDefault().getPath(
-
System.getProperty("user.home"), "www", "django.wsgi");
-
Path path_3 = FileSystems.getDefault().getPath(
-
System.getProperty("user.home"), "software/../www",
-
"pyweb.settings");
-
try {
-
boolean is_same_file_12 = Files.isSameFile(path_1, path_2);
-
boolean is_same_file_13 = Files.isSameFile(path_1, path_3);
-
boolean is_same_file_23 = Files.isSameFile(path_2, path_3);
-
System.out.println("is same file 1&2 ? " + is_same_file_12);
-
System.out.println("is same file 1&3 ? " + is_same_file_13);
-
System.out.println("is same file 2&3 ? " + is_same_file_23);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 检测文件可见行
-
try {
-
boolean is_hidden = Files.isHidden(path);
-
System.out.println("Is hidden ? " + is_hidden);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 获取文件系统根目录
-
Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
-
for (Path name : dirs) {
-
System.out.println(name);
-
}
-
// jdk6的API
-
// File[] roots = File.listRoots();
-
// for (File root : roots) {
-
// System.out.println(root);
-
// }
-
// 创建新目录
-
Path newdir = FileSystems.getDefault().getPath("/tmp/aaa");
-
// try {
-
// Files.createDirectory(newdir);
-
// } catch (IOException e) {
-
// System.err.println(e);
-
// }
-
Set<PosixFilePermission> perms = PosixFilePermissions
-
.fromString("rwxr-x---");
-
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions
-
.asFileAttribute(perms);
-
try {
-
Files.createDirectory(newdir, attr);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 创建多级目录,创建bbb目录,在bbb目录下再创建ccc目录等等
-
Path newdir2 = FileSystems.getDefault().getPath("/tmp/aaa",
-
"/bbb/ccc/ddd");
-
try {
-
Files.createDirectories(newdir2);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 列举目录信息
-
Path newdir3 = FileSystems.getDefault().getPath("/tmp");
-
try (DirectoryStream<Path> ds = Files.newDirectoryStream(newdir3)) {
-
for (Path file : ds) {
-
System.out.println(file.getFileName());
-
}
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 通过正则表达式过滤
-
System.out.println("\nGlob pattern applied:");
-
try (DirectoryStream<Path> ds = Files.newDirectoryStream(newdir3,
-
"*.{png,jpg,bmp,ini}")) {
-
for (Path file : ds) {
-
System.out.println(file.getFileName());
-
}
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 创建新文件
-
Path newfile = FileSystems.getDefault().getPath(
-
"/tmp/SonyEricssonOpen.txt");
-
Set<PosixFilePermission> perms1 = PosixFilePermissions
-
.fromString("rw-------");
-
FileAttribute<Set<PosixFilePermission>> attr2 = PosixFilePermissions
-
.asFileAttribute(perms1);
-
try {
-
Files.createFile(newfile, attr2);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 写小文件
-
try {
-
byte[] rf_wiki_byte = "test".getBytes("UTF-8");
-
Files.write(newfile, rf_wiki_byte);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 读小文件
-
try {
-
byte[] ballArray = Files.readAllBytes(newfile);
-
System.out.println(ballArray.toString());
-
} catch (IOException e) {
-
System.out.println(e);
-
}
-
Charset charset = Charset.forName("ISO-8859-1");
-
try {
-
List<String> lines = Files.readAllLines(newfile, charset);
-
for (String line : lines) {
-
System.out.println(line);
-
}
-
} catch (IOException e) {
-
System.out.println(e);
-
}
-
// 读写文件缓存流操作
-
String text = "\nVamos Rafa!";
-
try (BufferedWriter writer = Files.newBufferedWriter(newfile, charset,
-
StandardOpenOption.APPEND)) {
-
writer.write(text);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
try (BufferedReader reader = Files.newBufferedReader(newfile, charset)) {
-
String line = null;
-
while ((line = reader.readLine()) != null) {
-
System.out.println(line);
-
}
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 不用缓存的输入输出流
-
String racquet = "Racquet: Babolat AeroPro Drive GT";
-
byte data[] = racquet.getBytes();
-
try (OutputStream outputStream = Files.newOutputStream(newfile)) {
-
outputStream.write(data);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
String string = "\nString: Babolat RPM Blast 16";
-
try (OutputStream outputStream = Files.newOutputStream(newfile,
-
StandardOpenOption.APPEND);
-
BufferedWriter writer = new BufferedWriter(
-
new OutputStreamWriter(outputStream))) {
-
writer.write(string);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
int n;
-
try (InputStream in = Files.newInputStream(newfile)) {
-
while ((n = in.read()) != -1) {
-
System.out.print((char) n);
-
}
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 临时目录操作
-
String tmp_dir_prefix = "nio_";
-
try {
-
// passing null prefix
-
Path tmp_1 = Files.createTempDirectory(null);
-
System.out.println("TMP: " + tmp_1.toString());
-
// set a prefix
-
Path tmp_2 = Files.createTempDirectory(tmp_dir_prefix);
-
System.out.println("TMP: " + tmp_2.toString());
-
// 删除临时目录
-
Path basedir = FileSystems.getDefault().getPath("/tmp/aaa");
-
Path tmp_dir = Files.createTempDirectory(basedir, tmp_dir_prefix);
-
File asFile = tmp_dir.toFile();
-
asFile.deleteOnExit();
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
String tmp_file_prefix = "rafa_";
-
String tmp_file_sufix = ".txt";
-
try {
-
// passing null prefix/suffix
-
Path tmp_1 = Files.createTempFile(null, null);
-
System.out.println("TMP: " + tmp_1.toString());
-
// set a prefix and a suffix
-
Path tmp_2 = Files.createTempFile(tmp_file_prefix, tmp_file_sufix);
-
System.out.println("TMP: " + tmp_2.toString());
-
File asFile = tmp_2.toFile();
-
asFile.deleteOnExit();
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
// 删除文件
-
try {
-
boolean success = Files.deleteIfExists(newdir2);
-
System.out.println("Delete status: " + success);
-
} catch (IOException | SecurityException e) {
-
System.err.println(e);
-
}
-
// 拷贝文件
-
Path copy_from = Paths.get("/tmp", "draw_template.txt");
-
Path copy_to = Paths
-
.get("/tmp/bbb", copy_from.getFileName().toString());
-
try {
-
Files.copy(copy_from, copy_to);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
try (InputStream is = new FileInputStream(copy_from.toFile())) {
-
Files.copy(is, copy_to);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
//移动文件
-
Path movefrom = FileSystems.getDefault().getPath(
-
"C:/rafaelnadal/rafa_2.jpg");
-
Path moveto = FileSystems.getDefault().getPath(
-
"C:/rafaelnadal/photos/rafa_2.jpg");
-
try {
-
Files.move(movefrom, moveto, StandardCopyOption.REPLACE_EXISTING);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
}
-
}
输出:
-
true
-
false
-
The checked file is not accessible!
-
is same file 1&2 ? false
-
is same file 1&3 ? true
-
is same file 2&3 ? false
-
Is hidden ? false
-
/
-
java.nio.file.FileAlreadyExistsException: /tmp/aaa
-
.ICE-unix
-
gpg-LOz0cL
-
.org.chromium.Chromium.YKWsQJ
-
hsperfdata_weijianzhongwj
-
kde-weijianzhongwj
-
pulse-qKcxuRTsGUob
-
scim-im-agent-0.3.0.socket-1000@localhost:0.0
-
scim-helper-manager-socket-weijianzhongwj
-
ksocket-weijianzhongwj
-
virtuoso_Lh2135.ini
-
scim-socket-frontend-weijianzhongwj
-
scim-panel-socket:0-weijianzhongwj
-
.X0-lock
-
pulse-j0jluTvI3Pe6
-
sni-qt_kaccessibleapp_2026-mEz8Dy
-
.X11-unix
-
akonadi-weijianzhongwj.mjmToI
-
ssh-mfuayNh73d7Q
-
virt_1111
-
aaa
-
pulse-PKdhtXMmr18n
-
fcitx-socket-:0
-
Glob pattern applied:
-
[B@cd32e5
-
test
-
test
-
Vamos Rafa!
-
Racquet: Babolat AeroPro Drive GT
-
String: Babolat RPM Blast 16TMP: /tmp/3892364837850046417
-
TMP: /tmp/nio_5078970948266789689
-
TMP: /tmp/7342813580436243519.tmp
-
TMP: /tmp/rafa_47993266069276248.txt
-
Delete status: true
-
java.nio.file.NoSuchFileException: /tmp/draw_template.txt
-
java.io.FileNotFoundException: /tmp/draw_template.txt (没有那个文件或目录)
-
java.nio.file.NoSuchFileException: C:/rafaelnadal/rafa_2.jpg
人工智能技术向前发展,也必然会出现一些岗位被人工智能取代,但我们相信,随着人工智能的发展,会有更多的新的、属于未来的工作岗位出现,是社会发展的必然产物,我们能做的也许只能是与时俱进了
ichieh: 我想问问在windows下Files.createFile(pathName, attr)这个方法怎么用? 博主的是linux下的权限attr吧(12-02 15:00#1楼)
Java NIO Files.createFile() fails with NoSuchFileException
Files.createFile(path.resolve("digital.xls")) path的目录必须以及创建,否则会 Java NIO Files.createFile() fa...
简介 本页讨论读,写,创建和打开文件的细节。有各种各样的文件I / O方法可供选择。为了帮助理解API,下图以复杂性排列文件I / O方法 在图的最左侧是实用程序方法readAllBytes,r...
创建文件 Files类中提供了createFile()方法,该方法用于实现创建文件。该方法语法格式如下: Files.createFile(Path target) ...
前言: 在Windows编程中CreateFile函数是用得非常多的,由于它的参数比较多比较复杂,在使用的时候容易出现问题,在学习了MSDN的官方文档后打算将其原文翻译出来,以供参考,如有错误,...
Java文件IO操作应该抛弃File拥抱Paths和Files
Java7中文件IO发生了很大的变化,专门引入了很多新的类: import java.nio.file.DirectoryStream; import java.nio.file.FileSy...
不要在linux上使用java 7 Files的接口参数StandardOpenOption.DELETE_ON_CLOSE
疯狂Java学习笔记(76)------------NIO.2第二篇
Java NIO基础教程 一、Java NIO 概述 Java NIO 由以下几个核心部分组成: l Channels l Buffers l Selectors 虽然Java NIO 中...
相关热词
java7卸载 java7更新 java7笔试 java7兼容 java7特性
个人资料
粉丝
225
喜欢
179
评论
154
等级:
访问:
121万+
积分:
1万+
排名:
1141
最新文章
- 阿里零售通2019校园招聘
- ibatis-sqlmap和sourceforge.ibatis对sqlmap的变量处理的不同
- linux 进程管理相关命令汇总
- java itext包使用异常问题
- java web应用在tomcat下servlet api包冲突问题
个人分类
- acm8篇
- flash as1篇
- flex18篇
- java117篇
- java web开发22篇
- linux11篇
- web框架18篇
- 数据库32篇
- 脚本语言6篇
- c&c++3篇
- nosql6篇
- jetty&tomcat6篇
- 开源框架41篇
- 架构3篇
- 数据结构与算法5篇
- 服务器2篇
- 操作系统10篇
- 服务器(apache)4篇
- 插件1篇
- android2篇
- web前端4篇
- mac1篇
展开
归档
- 2018年2月1篇
- 2015年9月1篇
- 2015年6月2篇
- 2015年3月2篇
- 2014年6月2篇
- 2013年10月1篇
- 2013年9月1篇
- 2013年8月2篇
- 2013年7月1篇
- 2013年6月36篇
- 2013年5月13篇
- 2013年4月11篇
- 2013年3月7篇
- 2013年2月1篇
- 2013年1月10篇
- 2012年12月12篇
- 2012年11月14篇
- 2012年10月1篇
- 2012年9月11篇
- 2012年8月14篇
- 2012年7月9篇
- 2012年6月41篇
- 2012年5月20篇
- 2011年7月1篇
- 2010年6月1篇
- 2010年5月2篇
- 2010年4月1篇
- 2010年3月6篇
- 2010年2月2篇
- 2010年1月10篇
- 2009年12月15篇
- 2009年11月4篇
- 2009年10月8篇
- 2009年9月10篇
- 2009年8月7篇
展开
ITjava面试指南
热门文章
- Servlet3.0新特性使用详解
阅读量:31023
- 数据库select的默认排序
阅读量:21303
- java AIO学习
阅读量:21093
- jdk7和8的一些新特性介绍
阅读量:19545
- jython安装和使用
阅读量:17795
最新评论
- java7 NIO2(8)The ...
qq_37349626:第一个例子,中断线程,如果出现阻塞就会抛出异常InterruptedException
- java并发发送请求的示例
fantasic_van:代码都不完整,就不要发出来了。。。
- java7 NIO2(5) 文件和...
u013030100:然后呢?报错就完事了??
- ibatis报列名无效的一个异常分析
weixin_37598682:有解决方案吗
- java使用抓包获得应用发送的对外...
qq_38319397:撒大苏打
联系我们
请扫描二维码联系客服
400-660-0108
QQ客服 客服论坛
©2018 优快云版权所有 京ICP证09002463号
优快云 APP
-
1