package xyz.jangle.file.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
/**
* @author jangle E-mail: [email protected]
* @version 2018年10月21日 上午10:08:11
* 類說明
*/
public class OutputStreamTest {
private static String path = "d:/logs/test/a/a/";
private static String fileNameWriter = "JangleTestWriter.txt";
public static void main(String[] args) {
// testOutput();
// testInsertFile();
testWriter();
testFilesCopy();
}
/**
* 對Java 7 的NIO的使用Demo
*/
private static void testFilesCopy() {
Path pathFrom = Paths.get(path,fileNameWriter); // 1.1創建一個Path源
// Path pathFrom = Paths.get("d:","logs","test","a","a",fileNameWriter); // 創建一個Path,這種方式跟上面的方式等同。
Path pathTo = Paths.get(path, "2"+fileNameWriter); // 1.2創建一個輸出Path目標
try {
Files.copy(pathFrom, pathTo,StandardCopyOption.REPLACE_EXISTING); //1.3使用NIO複製文件, Option參數含義:若存在則替換
List<String> lines = Files.readAllLines(pathTo); // 2.1獲取目標文件文本內容的所有行。(使用NIO直接獲取文本內容,並輸出)
System.out.print("pathTo 的文件內容:");
for(String line:lines) {
System.out.println(line); //2.2輸出目標文件所有行內容
}
InputStream inputStream = Files.newInputStream(pathFrom); //3.1通過路徑獲取源文件 輸入流 (使用NIO獲取輸入流,再進行內容獲取,並輸出。)
byte[] b = new byte[inputStream.available()];
inputStream.read(b); // 3.2通過輸入流,將字節讀入字節數組中。
System.out.print("pathFrom的文件內容:");
System.out.println(new String(b,StandardCharsets.UTF_8)); //3.3將原本的文本字節進行編碼成字符串輸出。
System.out.println("1.5的目標文件內容和2.3的源文件的內容一致。 複製是成功的。");
Files.delete(pathTo); //4.1使用NIO刪除目標文件
boolean existsPathTo = pathTo.toFile().exists(); //4.2將Path轉換爲File對象,並判斷是否存在文件。
System.out.println("執行刪除後,pathTo對應的文件是否存在:"+existsPathTo);
Files.move(pathFrom, pathTo); //4.3使用NIO將文件進行移動
System.out.println("執行移動後,pathTo 對應的文件是否存在:"+pathTo.toFile().exists());
System.out.println("執行移動後,pathFrom對應的文件是否存在:"+pathTo.toFile().exists());
Files.move(pathTo, pathFrom); //移動回來
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用Writer進行文本內容輸入。
*/
private static void testWriter() {
File filePath = new File(path);
if(!filePath.exists()) {
filePath.mkdirs();
}
File file = new File(path+fileNameWriter);
try {
FileOutputStream out = new FileOutputStream(file,true); //第二個參數表示是否添加
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out,StandardCharsets.UTF_8);
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print("歡迎訪問http://jangle.xyz");
printWriter.flush();
printWriter.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("ok");
}
}
主要是對 Path接口 和 Files類的使用。
java.nio.file.Path:路徑,表示的是一個目錄名序列,其後還可以跟着文件名。
java.nio.file.Files:使普通文件操作變得快捷,更容易地讀取文件的所有內容。
參考文獻:Java核心技術 卷II (原書第11版)P86-93