javaNIO 學習筆記(五)
本片大多數內容大多都是翻譯參考文檔。
file(java.nio.file.Files)
Java NIO文件類提供了幾種在文件系統中操作文件的方法
// 檢查文件系統中是否存在給定路徑
Files.exists(Path path, LinkOption... options)
// 若創建的目錄存在會拋異常 FileAlreadyExistsException
Files.createDirectory(Path path)
// 如果目標文件已經存在拋出FileAlreadyExistsException如果要將文件複製到的目錄不存在,就會拋出IOException
Files.copy()
// 覆蓋現有的文件
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
// 將文件從一個路徑移動到另一個路徑
Files.move()
Files.delete()
// 遍歷 path目錄,操作接口
Files.walkFileTree(Path,FileVisitor)
FileVisitor裏面的方法都是返回一個FileVisitResult(枚舉)
CONTINUE 繼續
TERMINATE 終止:文件遍歷現在應該終止
SKIP_SIBLING 跳過同級 :文件遍歷應該繼續,但不需要訪問該文件或目錄的任何同級
SKIP_SUBTREE 跳過子級:文件遍歷應該繼續,但是不需要訪問這個目錄中的子目錄
package jniolearn;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: jimmy
* @Date: 2020/6/16 00:29
* @Description:
*/
public class FilePrc {
public static void main(String[] args) throws FileNotFoundException, IOException {
//將傳統io讀寫文件高度封裝之後,在NIO.2中拷貝文件只需要調用File工具類的copy()方法
Files.copy(Paths.get("tmp.txt"), new FileOutputStream("tmp2.txt"));
//是否爲隱藏文件
System.out.println("tmp.txt是否爲隱藏文件: "+Files.isHidden(Paths.get("tmp.txt")));
//一次性讀取所有行 , 需要指定編碼規則
List<String> lines = Files.readAllLines(Paths.get("tmp.txt"), Charset.forName("gbk"));
System.out.println(lines);
//文件大小
System.out.println("tmp.txt文件大小爲: "+Files.size(Paths.get("tmp.txt")));
List<String> poem = new ArrayList<>();
poem.add("海闊憑魚躍");
poem.add("天高任鳥飛");
//直接將字符串數組寫入文件
Files.write(Paths.get("tmp.txt"), poem, Charset.forName("gbk"));
}
}
AsynchronousFileChannel
AsynchronousFileChannel
是Java 7中添加的
Path path = Paths.get("data/test.xml");
// 第一個參數是指向與AsynchronousFileChannel相關聯的文件的Path實例
// 第二個參數是一個或多個打開選項
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ);
讀取數據
- Future
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
Future<Integer> operation = fileChannel.read(buffer, position);
while(!operation.isDone());
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
buffer.clear();
- CompletionHandler
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@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();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
一旦讀取操作完成,將調用CompletionHandler
的completed()
方法。對於completed()
方法的參數傳遞一個整數,它告訴我們讀取了多少字節,以及傳遞給read()
方法的“附件”。“附件”是read()
方法的第三個參數。在本例中,它是ByteBuffer
,數據也被讀取。如果讀取操作失敗,則將調用CompletionHandler
的failed()
方法。
寫數據
- Future
Path path = Paths.get("data/test-write.txt");
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");
- 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();
}
});