Java Stream,File,IO

java包之java.io

NIO

  • 由于下面的系列教程只翻译到了13,后面的也挺简单的。主要是代码。记录在这里。
  • 重点参考:java NIO系列教程

15 Java NIO Path

  • 翻译自:15Java NIO Path
  • Java的java.nio.file.Path接口是JavaNIO 2 update的一部分,在Java6和Java7中得到更新。Java path接口在java7中被加入到Java NIO中。Path接口位于java.nio.file包中,所以Java Path接口的全名是:java.nio.file.Path。
  • 一个Java Path接口代表了一个文件系统中的path路径。path路径可以指向文件或目录。一个路径可以是绝对路径也可以是相对路径。一个绝对路径是从文件系统根目录指向该文件或路径的全路径。一个相对路径是指相对于其他路径一个文件或目录的相对路径。相对路径可能比较费解,不用担心,我会在该文中详细介绍。
  • 对于操作系统中的系统路径这样的环境变量不要疑惑,java Path接口跟它们没有关系。
  • 在很多方面java.nio.file.Path和java.io.File类是类似的,在一些地方你可以使用Path接口来代替File类,但是也有一些不同。

1. 创建Path实例

  • 你可以使用java.nio.file.Paths类的静态方法Paths.get()来创建一个java.nio.file.Path的实例:
import java.nio.file.Path;
import java.nio.file.Paths; public class PathExample { public static void main(String[] args) { Path path = Paths.get("c:\\data\\myfile.txt"); }
}
  • Paths.get()方法是创建Path实例的工厂方法。

2. 创建一个绝对路径Path实例

  • Windows文件系统下的绝对路径:
Path path = Paths.get("c:\\data\\myfile.txt");
  • 类Unix操作系统下的绝对路径:
Path path = Paths.get("/home/jakobjenkov/myfile.txt");
//如果你在windows上这么使用,会表示当前系统分区下的路径,如:C:/home/jakobjenkov/myfile.txt

3. 创建一个相对路径Path实例

  • 相对路径需要一个basepath和relativepath来创建:
Path projects = Paths.get("d:\\data", "projects");

Path file     = Paths.get("d:\\data", "projects\\a-project\\myfile.txt");
  • 可以使用'.','..'来创建路径实例:
Path currentDir = Paths.get(".");
System.out.println(currentDir.toAbsolutePath());

4. Path.normalize()

String originalPath =
"d:\\data\\projects\\a-project\\..\\another-project"; Path path1 = Paths.get(originalPath);
System.out.println("path1 = " + path1); Path path2 = path1.normalize();
System.out.println("path2 = " + path2);
path1 = d:\data\projects\a-project\..\another-project
path2 = d:\data\projects\another-project

16. Java NIO Files

  • 翻译自:16Java NIO Files
  • java.nio.file.Files类提供了多种方法来操作文件。

1. Files.exists()

  • LinkOption.NOFOLLOW_LINKS表示文件存在,但是不能是链接形式的。
Path path = Paths.get("data/logging.properties");

boolean pathExists =
Files.exists(path,
new LinkOption[]{ LinkOption.NOFOLLOW_LINKS});

2. Files.createDirectory()

Path path = Paths.get("data/subdir");

try {
Path newDir = Files.createDirectory(path);
} catch(FileAlreadyExistsException e){
// the directory already exists.
} catch (IOException e) {
//something else went wrong
e.printStackTrace();
}

3. Files.copy()

Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties"); try {
Files.copy(sourcePath, destinationPath);
} catch(FileAlreadyExistsException e) {
//destination file already exists
} catch (IOException e) {
//something else went wrong
e.printStackTrace();
}

4. Overwriting Existing Files

  • 通过复制选项来覆盖已经存在的Files
Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties"); try {
Files.copy(sourcePath, destinationPath,
StandardCopyOption.REPLACE_EXISTING);
} catch(FileAlreadyExistsException e) {
//destination file already exists
} catch (IOException e) {
//something else went wrong
e.printStackTrace();
}

5. Files.move()

  • java.io.File 有方法 renameTo() ,Files可以Files.move()
Path sourcePath      = Paths.get("data/logging-copy.properties");
Path destinationPath = Paths.get("data/subdir/logging-moved.properties"); try {
Files.move(sourcePath, destinationPath,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
//moving file failed.
e.printStackTrace();
}

6. Files.delete()

Path path = Paths.get("data/subdir/logging-moved.properties");

try {
Files.delete(path);
} catch (IOException e) {
//deleting file failed
e.printStackTrace();
}

7. Files.walkFileTree()

  • Files.walkFileTree()用来递归遍历文件目录,有Path实例和FileVisitor来做参数。
  • FileVisitor接口有如下形式:
public interface FileVisitor {

    public FileVisitResult preVisitDirectory(
Path dir, BasicFileAttributes attrs) throws IOException; public FileVisitResult visitFile(
Path file, BasicFileAttributes attrs) throws IOException; public FileVisitResult visitFileFailed(
Path file, IOException exc) throws IOException; public FileVisitResult postVisitDirectory(
Path dir, IOException exc) throws IOException { }
  • FileVisitor有一个简单实现SimpleFileVisitor类:
Files.walkFileTree(path, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
System.out.println("pre visit dir:" + dir);
return FileVisitResult.CONTINUE;
} @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("visit file: " + file);
return FileVisitResult.CONTINUE;
} @Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("visit file failed: " + file);
return FileVisitResult.CONTINUE;
} @Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
System.out.println("post visit directory: " + dir);
return FileVisitResult.CONTINUE;
}
}); - FileVisitResult的集合有:
CONTINUE 表示继续
TERMINATE 表示停止
SKIP_SIBLINGS 表示继续但是不再便利兄弟目录
SKIP_SUBTREE 表示继续但是不再便利子目录

8. Searching For Files

  • 下面可以实现SimpleFileVisitor来查找文件:
Path rootPath = Paths.get("data");
String fileToFind = File.separator + "README.txt"; try {
Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() { @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileString = file.toAbsolutePath().toString();
//System.out.println("pathString = " + fileString); if(fileString.endsWith(fileToFind)){
System.out.println("file found at path: " + file.toAbsolutePath());
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
} catch(IOException e){
e.printStackTrace();
}

9. Deleting Directories Recursively

Path rootPath = Paths.get("data/to-delete");

try {
Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("delete file: " + file.toString());
Files.delete(file);
return FileVisitResult.CONTINUE;
} @Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
System.out.println("delete dir: " + dir.toString());
return FileVisitResult.CONTINUE;
}
});
} catch(IOException e){
e.printStackTrace();
}

10. Additional Methods in the Files Class

  • Files类有很多其他方法,如 creating symbolic links, determining the file size, setting file permissions 等。参考java文档。

17. Java NIO AsynchronousFileChannel

  • java7中AsynchronousFileChannel加入到了java NIO的包中。AsynchronousFileChannels使得异步读写文件实现。

1. Creating an AsynchronousFileChannel

Path path = Paths.get("data/test.xml");

AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ);

2. Reading Data

  • Reading Data Via a Future
Future<Integer> operation = fileChannel.read(buffer, 0);
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0; Future<Integer> operation = fileChannel.read(buffer, position);
// Of course, this is not a very efficient use of the CPU - but somehow you need to wait until the read operation has completed. while(!operation.isDone()); buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
buffer.clear();
  • Reading Data Via a CompletionHandler
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {
//Once the read operation finishes the CompletionHandler's completed() method will be called.
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("result = " + result); attachment.flip();
byte[] data = new byte[attachment.limit()];
attachment.get(data);
System.out.println(new String(data));
attachment.clear();
}
//If the read operation fails, the failed() method of the CompletionHandler will get called instead.
@Override
public void failed(Throwable exc, ByteBuffer attachment) { }
});

3. Writing Data

  • Writing Data Via a Future

Path path = Paths.get("data/test-write.txt");
//If the file does not exist the write() method will throw a java.nio.file.NoSuchFileException .
if(!Files.exists(path)){
Files.createFile(path);
}
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0; buffer.put("test data".getBytes());
buffer.flip(); Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear(); while(!operation.isDone()); System.out.println("Write done");
  • Writing Data Via a CompletionHandler
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0; buffer.put("test data".getBytes());
buffer.flip(); fileChannel.write(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("bytes written: " + result);
} @Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("Write failed");
exc.printStackTrace();
}
});

Java基础之IO和NIO补完的更多相关文章

  1. Java基础差,需要怎么补

    本文首发于本博客 猫叔的博客,转载请申明出处 感谢sugar的提问:Java基础差,需要怎么补? 欢迎关注公众号:Java猫说 我整体的总结了一下,大致分为以下的几个点说一下: 1.善于使用搜索引擎 ...

  2. java基础之IO流(二)之字符流

    java基础之IO流(二)之字符流 字符流,顾名思义,它是以字符为数据处理单元的流对象,那么字符流和字节流之间的关系又是如何呢? 字符流可以理解为是字节流+字符编码集额一种封装与抽象,专门设计用来读写 ...

  3. java基础之IO流(一)字节流

    java基础之IO流(一)之字节流 IO流体系太大,涉及到的各种流对象,我觉得很有必要总结一下. 那什么是IO流,IO代表Input.Output,而流就是原始数据源与目标媒介的数据传输的一种抽象.典 ...

  4. Java基础之IO流整理

    Java基础之IO流 Java IO流使用装饰器设计模式,因此如果不能理清其中的关系的话很容易把各种流搞混,此文将简单的几个流进行梳理,后序遇见新的流会继续更新(本文下方还附有xmind文件链接) 抽 ...

  5. Java中的IO、NIO、File、BIO、AIO详解

    java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类?         Java中的流分为两种,一种是字节流,另一种是字符流,分别由四个抽象类来表示(每种流包 ...

  6. java面试:java基础、Io、容器

    1.java基础 1.JDK 和JRE有什么区别 ​ JDK:java开发工具包,java开发运行环境.包含了JRE. ​ JRE:java运行环境,包含java虚拟机,java基础类库. 2.jav ...

  7. Java基础之IO技术(一)

    ---恢复内容开始--- Java基础中的IO技术可谓是非常重要,俗话说的好,万丈高楼起于垒土之间.所以学习Java一定要把基础学好,今天我们来学习IO技术的基础. IO无非就是输入与输出,而其中处理 ...

  8. java基础知识----IO篇

    写在前面:本文章基本覆盖了java IO的所有内容.java新IO没有涉及.文章依然以样例为主,由于解说内容的java书非常多了,我觉的学以致用才是真.代码是写出来的,不是看出来的. 最后欢迎大家提出 ...

  9. Java中的IO与NIO

    前文开了高并发学习的头,文末说了将会选择NIO.RPC相关资料做进一步学习,所以本文开始学习NIO知识. IO知识回顾 在学习NIO前,有必要先回顾一下IO的一些知识. IO中的流 Java程序通过流 ...

随机推荐

  1. POJ 3616 Milking Time ——(记忆化搜索)

    第一眼看是线段交集问题,感觉不会= =.然后发现n是1000,那好像可以n^2建图再做.一想到这里,突然醒悟,直接记忆化搜索就好了啊..太蠢了.. 代码如下: #include <stdio.h ...

  2. Ubuntu系统图形化界面无法登录到root用户的解决方法

    Ubuntu默认是禁用了root用户的登录. 系统安装后, 图形化界面无法登录到root用户解决方法:Ubuntu 12.04:1.设置root用户密码:  普通用户登录,sudo passwd ro ...

  3. 安装Oracle11g出现INS-13001环境不满足最低要求

    原版:https://blog.csdn.net/Q_Sea__/article/details/79012808 第一次安装Oracle11g,就出现这个问题,就找了一些解决方案.现在总结一下. 出 ...

  4. Mask_RCNN

  5. BSD process name correspondlng to current thread: knernel_task Mac OS version Not yet set

    网上查了一大堆,没有一个靠谱的, 百度,以说黑苹果装系统最容易出现这个,这个让我开始怀疑公司给我们的所谓外观的iMac是黑苹果了,因为一直很卡,比上家公司的真黑苹果还卡. 谷歌,有说重置BIOS电池的 ...

  6. MYSQL的MYSQLDUMP命令

    1.用mysqldump对MySQL数据库进行数据备份与恢复 下面假设要备份tm这个数据库:Shell>mysqldump -uroot –p123456 tm > tm_050519.s ...

  7. windows10专业版激活方法

    1.首先在桌面左下角的“cortana”搜索框中输入“CMD”,待出现“命令提示符”工具时,右击选择“以管理员身份”运行. 2.此时将“以管理员身份”打开“MSDOS”窗口,在此界面中,依次输出以下命 ...

  8. Jetson TX2 不同的工作模式

    Jetson TX2 有五种工作模式,下面介绍这几种工作模式下电压.频率以及如何启动. 原理图 几种不同的工作模式 mode mode name Denver Frequency ARM Freque ...

  9. 利用matlab自带函数快速提取二值图像的图像边缘 bwperim函数

      clear all;close all;clc; I = imread('rice.png'); I = im2bw(I); J = bwperim(I); % 提取二值图像图像边缘 figure ...

  10. django 之(五) --- RESTApi总结

    RESTful django-rest-framework serializers 序列化工具.序列化与反序列化 级联模型 添加级联字段 nested 级联字段的key原来必须就是存在的 隐性属性.自 ...