File nio操作转载

java7 NIO2(4) 文件和目录操作API

2012年12月30日 16:24:16 阅读数:10431更多

个人分类: java

文件和目录操作API,跟原来FILE IO做了很多改进,我们看看新的API,这个也是NIO操作的基础。

 

 
  1. package com.mime;

  2.  
  3. import java.io.BufferedReader;

  4. import java.io.BufferedWriter;

  5. import java.io.File;

  6. import java.io.FileInputStream;

  7. import java.io.IOException;

  8. import java.io.InputStream;

  9. import java.io.OutputStream;

  10. import java.io.OutputStreamWriter;

  11. import java.nio.charset.Charset;

  12. import java.nio.file.DirectoryStream;

  13. import java.nio.file.FileSystems;

  14. import java.nio.file.Files;

  15. import java.nio.file.LinkOption;

  16. import java.nio.file.Path;

  17. import java.nio.file.Paths;

  18. import java.nio.file.StandardCopyOption;

  19. import java.nio.file.StandardOpenOption;

  20. import java.nio.file.attribute.FileAttribute;

  21. import java.nio.file.attribute.PosixFilePermission;

  22. import java.nio.file.attribute.PosixFilePermissions;

  23. import java.util.List;

  24. import java.util.Set;

  25.  
  26. public class NIO2FileAndDir {

  27.  
  28. /**

  29. * @param args

  30. */

  31. public static void main(String[] args) {

  32. Path path = FileSystems.getDefault().getPath(

  33. System.getProperty("user.home"), "www", "pyweb.settings");

  34. // 检查文件是否存在 exist, not exist, or unknown.

  35. // !Files.exists(...) is not equivalent to Files.notExists(...) and the

  36. // notExists() method is not a complement of the exists() method

  37. // 如果应用没有权限访问这个文件,则两者都返回false

  38. boolean path_exists = Files.exists(path,

  39. new LinkOption[] { LinkOption.NOFOLLOW_LINKS });

  40. boolean path_notexists = Files.notExists(path,

  41. new LinkOption[] { LinkOption.NOFOLLOW_LINKS });

  42. System.out.println(path_exists);

  43. System.out.println(path_notexists);

  44.  
  45. // 检测文件访问权限

  46. boolean is_readable = Files.isReadable(path);

  47. boolean is_writable = Files.isWritable(path);

  48. boolean is_executable = Files.isExecutable(path);

  49. boolean is_regular = Files.isRegularFile(path,

  50. LinkOption.NOFOLLOW_LINKS);

  51. if ((is_readable) && (is_writable) && (is_executable) && (is_regular)) {

  52. System.out.println("The checked file is accessible!");

  53. } else {

  54. System.out.println("The checked file is not accessible!");

  55. }

  56.  
  57. // 检测文件是否指定同一个文件

  58. Path path_1 = FileSystems.getDefault().getPath(

  59. System.getProperty("user.home"), "www", "pyweb.settings");

  60. Path path_2 = FileSystems.getDefault().getPath(

  61. System.getProperty("user.home"), "www", "django.wsgi");

  62. Path path_3 = FileSystems.getDefault().getPath(

  63. System.getProperty("user.home"), "software/../www",

  64. "pyweb.settings");

  65. try {

  66. boolean is_same_file_12 = Files.isSameFile(path_1, path_2);

  67. boolean is_same_file_13 = Files.isSameFile(path_1, path_3);

  68. boolean is_same_file_23 = Files.isSameFile(path_2, path_3);

  69. System.out.println("is same file 1&2 ? " + is_same_file_12);

  70. System.out.println("is same file 1&3 ? " + is_same_file_13);

  71. System.out.println("is same file 2&3 ? " + is_same_file_23);

  72. } catch (IOException e) {

  73. System.err.println(e);

  74. }

  75.  
  76. // 检测文件可见行

  77. try {

  78. boolean is_hidden = Files.isHidden(path);

  79. System.out.println("Is hidden ? " + is_hidden);

  80. } catch (IOException e) {

  81. System.err.println(e);

  82. }

  83.  
  84. // 获取文件系统根目录

  85. Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();

  86. for (Path name : dirs) {

  87. System.out.println(name);

  88. }

  89. // jdk6的API

  90. // File[] roots = File.listRoots();

  91. // for (File root : roots) {

  92. // System.out.println(root);

  93. // }

  94.  
  95. // 创建新目录

  96. Path newdir = FileSystems.getDefault().getPath("/tmp/aaa");

  97. // try {

  98. // Files.createDirectory(newdir);

  99. // } catch (IOException e) {

  100. // System.err.println(e);

  101. // }

  102. Set<PosixFilePermission> perms = PosixFilePermissions

  103. .fromString("rwxr-x---");

  104. FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions

  105. .asFileAttribute(perms);

  106. try {

  107. Files.createDirectory(newdir, attr);

  108. } catch (IOException e) {

  109. System.err.println(e);

  110. }

  111.  
  112. // 创建多级目录,创建bbb目录,在bbb目录下再创建ccc目录等等

  113. Path newdir2 = FileSystems.getDefault().getPath("/tmp/aaa",

  114. "/bbb/ccc/ddd");

  115. try {

  116. Files.createDirectories(newdir2);

  117. } catch (IOException e) {

  118. System.err.println(e);

  119. }

  120.  
  121. // 列举目录信息

  122. Path newdir3 = FileSystems.getDefault().getPath("/tmp");

  123. try (DirectoryStream<Path> ds = Files.newDirectoryStream(newdir3)) {

  124. for (Path file : ds) {

  125. System.out.println(file.getFileName());

  126. }

  127. } catch (IOException e) {

  128. System.err.println(e);

  129. }

  130. // 通过正则表达式过滤

  131. System.out.println("\nGlob pattern applied:");

  132. try (DirectoryStream<Path> ds = Files.newDirectoryStream(newdir3,

  133. "*.{png,jpg,bmp,ini}")) {

  134. for (Path file : ds) {

  135. System.out.println(file.getFileName());

  136. }

  137. } catch (IOException e) {

  138. System.err.println(e);

  139. }

  140.  
  141. // 创建新文件

  142. Path newfile = FileSystems.getDefault().getPath(

  143. "/tmp/SonyEricssonOpen.txt");

  144. Set<PosixFilePermission> perms1 = PosixFilePermissions

  145. .fromString("rw-------");

  146. FileAttribute<Set<PosixFilePermission>> attr2 = PosixFilePermissions

  147. .asFileAttribute(perms1);

  148. try {

  149. Files.createFile(newfile, attr2);

  150. } catch (IOException e) {

  151. System.err.println(e);

  152. }

  153.  
  154. // 写小文件

  155. try {

  156. byte[] rf_wiki_byte = "test".getBytes("UTF-8");

  157. Files.write(newfile, rf_wiki_byte);

  158. } catch (IOException e) {

  159. System.err.println(e);

  160. }

  161.  
  162. // 读小文件

  163. try {

  164. byte[] ballArray = Files.readAllBytes(newfile);

  165. System.out.println(ballArray.toString());

  166. } catch (IOException e) {

  167. System.out.println(e);

  168. }

  169. Charset charset = Charset.forName("ISO-8859-1");

  170. try {

  171. List<String> lines = Files.readAllLines(newfile, charset);

  172. for (String line : lines) {

  173. System.out.println(line);

  174. }

  175. } catch (IOException e) {

  176. System.out.println(e);

  177. }

  178.  
  179. // 读写文件缓存流操作

  180. String text = "\nVamos Rafa!";

  181. try (BufferedWriter writer = Files.newBufferedWriter(newfile, charset,

  182. StandardOpenOption.APPEND)) {

  183. writer.write(text);

  184. } catch (IOException e) {

  185. System.err.println(e);

  186. }

  187. try (BufferedReader reader = Files.newBufferedReader(newfile, charset)) {

  188. String line = null;

  189. while ((line = reader.readLine()) != null) {

  190. System.out.println(line);

  191. }

  192. } catch (IOException e) {

  193. System.err.println(e);

  194. }

  195.  
  196. // 不用缓存的输入输出流

  197. String racquet = "Racquet: Babolat AeroPro Drive GT";

  198. byte data[] = racquet.getBytes();

  199. try (OutputStream outputStream = Files.newOutputStream(newfile)) {

  200. outputStream.write(data);

  201. } catch (IOException e) {

  202. System.err.println(e);

  203. }

  204. String string = "\nString: Babolat RPM Blast 16";

  205. try (OutputStream outputStream = Files.newOutputStream(newfile,

  206. StandardOpenOption.APPEND);

  207. BufferedWriter writer = new BufferedWriter(

  208. new OutputStreamWriter(outputStream))) {

  209. writer.write(string);

  210. } catch (IOException e) {

  211. System.err.println(e);

  212. }

  213. int n;

  214. try (InputStream in = Files.newInputStream(newfile)) {

  215. while ((n = in.read()) != -1) {

  216. System.out.print((char) n);

  217. }

  218. } catch (IOException e) {

  219. System.err.println(e);

  220. }

  221.  
  222. // 临时目录操作

  223. String tmp_dir_prefix = "nio_";

  224. try {

  225. // passing null prefix

  226. Path tmp_1 = Files.createTempDirectory(null);

  227. System.out.println("TMP: " + tmp_1.toString());

  228. // set a prefix

  229. Path tmp_2 = Files.createTempDirectory(tmp_dir_prefix);

  230. System.out.println("TMP: " + tmp_2.toString());

  231.  
  232. // 删除临时目录

  233. Path basedir = FileSystems.getDefault().getPath("/tmp/aaa");

  234. Path tmp_dir = Files.createTempDirectory(basedir, tmp_dir_prefix);

  235. File asFile = tmp_dir.toFile();

  236. asFile.deleteOnExit();

  237.  
  238. } catch (IOException e) {

  239. System.err.println(e);

  240. }

  241.  
  242. String tmp_file_prefix = "rafa_";

  243. String tmp_file_sufix = ".txt";

  244. try {

  245. // passing null prefix/suffix

  246. Path tmp_1 = Files.createTempFile(null, null);

  247. System.out.println("TMP: " + tmp_1.toString());

  248. // set a prefix and a suffix

  249. Path tmp_2 = Files.createTempFile(tmp_file_prefix, tmp_file_sufix);

  250. System.out.println("TMP: " + tmp_2.toString());

  251. File asFile = tmp_2.toFile();

  252. asFile.deleteOnExit();

  253.  
  254. } catch (IOException e) {

  255. System.err.println(e);

  256. }

  257.  
  258. // 删除文件

  259. try {

  260. boolean success = Files.deleteIfExists(newdir2);

  261. System.out.println("Delete status: " + success);

  262. } catch (IOException | SecurityException e) {

  263. System.err.println(e);

  264. }

  265.  
  266. // 拷贝文件

  267. Path copy_from = Paths.get("/tmp", "draw_template.txt");

  268. Path copy_to = Paths

  269. .get("/tmp/bbb", copy_from.getFileName().toString());

  270. try {

  271. Files.copy(copy_from, copy_to);

  272. } catch (IOException e) {

  273. System.err.println(e);

  274. }

  275. try (InputStream is = new FileInputStream(copy_from.toFile())) {

  276. Files.copy(is, copy_to);

  277. } catch (IOException e) {

  278. System.err.println(e);

  279. }

  280. //移动文件

  281. Path movefrom = FileSystems.getDefault().getPath(

  282. "C:/rafaelnadal/rafa_2.jpg");

  283. Path moveto = FileSystems.getDefault().getPath(

  284. "C:/rafaelnadal/photos/rafa_2.jpg");

  285. try {

  286. Files.move(movefrom, moveto, StandardCopyOption.REPLACE_EXISTING);

  287. } catch (IOException e) {

  288. System.err.println(e);

  289. }

  290.  
  291. }

  292.  
  293. }


输出:

 

 
  1. true

  2. false

  3. The checked file is not accessible!

  4. is same file 1&2 ? false

  5. is same file 1&3 ? true

  6. is same file 2&3 ? false

  7. Is hidden ? false

  8. /

  9. java.nio.file.FileAlreadyExistsException: /tmp/aaa

  10. .ICE-unix

  11. gpg-LOz0cL

  12. .org.chromium.Chromium.YKWsQJ

  13. hsperfdata_weijianzhongwj

  14. kde-weijianzhongwj

  15. pulse-qKcxuRTsGUob

  16. scim-im-agent-0.3.0.socket-1000@localhost:0.0

  17. scim-helper-manager-socket-weijianzhongwj

  18. ksocket-weijianzhongwj

  19. virtuoso_Lh2135.ini

  20. scim-socket-frontend-weijianzhongwj

  21. scim-panel-socket:0-weijianzhongwj

  22. .X0-lock

  23. pulse-j0jluTvI3Pe6

  24. sni-qt_kaccessibleapp_2026-mEz8Dy

  25. .X11-unix

  26. akonadi-weijianzhongwj.mjmToI

  27. ssh-mfuayNh73d7Q

  28. virt_1111

  29. aaa

  30. pulse-PKdhtXMmr18n

  31. fcitx-socket-:0

  32.  
  33. Glob pattern applied:

  34. [B@cd32e5

  35. test

  36. test

  37. Vamos Rafa!

  38. Racquet: Babolat AeroPro Drive GT

  39. String: Babolat RPM Blast 16TMP: /tmp/3892364837850046417

  40. TMP: /tmp/nio_5078970948266789689

  41. TMP: /tmp/7342813580436243519.tmp

  42. TMP: /tmp/rafa_47993266069276248.txt

  43. Delete status: true

  44. java.nio.file.NoSuchFileException: /tmp/draw_template.txt

  45. java.io.FileNotFoundException: /tmp/draw_template.txt (没有那个文件或目录)

  46. java.nio.file.NoSuchFileException: C:/rafaelnadal/rafa_2.jpg

 

人工智能工程师凭什么这么值钱

人工智能技术向前发展,也必然会出现一些岗位被人工智能取代,但我们相信,随着人工智能的发展,会有更多的新的、属于未来的工作岗位出现,是社会发展的必然产物,我们能做的也许只能是与时俱进了

  • Pan_cras

    ichieh: 我想问问在windows下Files.createFile(pathName, attr)这个方法怎么用? 博主的是linux下的权限attr吧(12-02 15:00#1楼)

Java NIO Files.createFile() fails with NoSuchFileException

qdqht2009

 1997

Files.createFile(path.resolve("digital.xls")) path的目录必须以及创建,否则会 Java NIO Files.createFile() fa...

File IO(NIO.2):读、写并创建文件

u013034889

 723

简介 本页讨论读,写,创建和打开文件的细节。有各种各样的文件I / O方法可供选择。为了帮助理解API,下图以复杂性排列文件I / O方法 在图的最左侧是实用程序方法readAllBytes,r...

 

使用Java8 Files类读写文件

infoflow

 4302

Java8 Files类的newBufferedReader()和newBufferedWriter()方法这两个方法接受Path类型的参数。Path 类是Java8 NIO中的接口。可以右Paths...

Files类

dwenxue

 236

创建文件        Files类中提供了createFile()方法,该方法用于实现创建文件。该方法语法格式如下:        Files.createFile(Path target)    ...

CreateFile 函数详细解析

li_wen01

 1347

前言:    在Windows编程中CreateFile函数是用得非常多的,由于它的参数比较多比较复杂,在使用的时候容易出现问题,在学习了MSDN的官方文档后打算将其原文翻译出来,以供参考,如有错误,...

Java文件IO操作应该抛弃File拥抱Paths和Files

u010889616

 1364

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

 

不要在linux上使用java 7 Files的接口参数StandardOpenOption.DELETE_ON_CLOSE

raintungli

 2524

最近在看安全代码规范建议中提到关于如何删除创建的临时文件,推荐使用jdk7中的Files的函数,通过参数StandardOpenOption.DELETE_ON_CLOSE来控制 代码示例 Buffe...

Java 复制大文件方式FileChannel 用法

bestone0213

 1516

目前为止,我们已经学习了很多 Java 拷贝文件的方式,除了 FileChannel 提供的方法外,还包括使用 Files.copy() 或使用字节数组的缓冲/非缓冲流。那个才是最好的选择呢?这个问题...

疯狂Java学习笔记(76)------------NIO.2第二篇

u011225629

 5949

上一篇地址http://write.blog.youkuaiyun.com/postedit/46386609 在该系列的上一篇中我演示了NIO.2的三个方法:文件拷贝、文件和目录的删除和文件移动。在这篇文章中...

Java NIO系列教程

yang_jie_3

 9

Java NIO基础教程 一、Java NIO 概述 Java NIO 由以下几个核心部分组成: l Channels l Buffers l Selectors 虽然Java NIO 中...

相关热词

java7卸载 java7更新 java7笔试 java7兼容 java7特性

个人资料

zhongweijian

关注

原创

262

粉丝

225

喜欢

179

评论

154

等级:

 

访问:

 

121万+

积分:

 

1万+

排名:

 

1141

 

最新文章

个人分类

展开

归档

展开

ITjava面试指南

直通BAT java面试课程

热门文章

最新评论

 

联系我们

客服

请扫描二维码联系客服

webmaster@youkuaiyun.com

400-660-0108

QQ客服 客服论坛

关于招聘广告服务 网站地图

©2018 优快云版权所有 京ICP证09002463号

百度提供搜索支持

app

经营性网站备案信息

网络110报警服务

中国互联网举报中心

北京互联网违法和不良信息举报中心

优快云 APP

  • 1

  • 1

  •  
  •  
  •  
  •  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值