Java IO流的基本使用 用法總結

(1)創建目錄及文件

/**
 * 基於指定文件名稱創建目錄及文件
 * 如果文件已經存在,則忽略
 *
 * @param fileName
 * @throws IOException 
 */
private static void createFile(String fileName) throws IOException {
	Path dir = Paths.get(fileName);
	Files.createDirectories(dir.getParent());// 創建目錄,存在目錄也不會拋出異常
	try{
		Files.createFile(dir);// 創建文件,若文件已經存在則會拋出異常
		System.out.println("創建文件成功!文件位置:" + fileName);
	}
	catch(FileAlreadyExistsException e) {
		System.out.println("文件 " + fileName + " 已存在,無需創建!");
	}
	System.out.println();
}

(2)基於BufferedWriter寫入文件

/**
 * 提示:文件以字節操作,因此可以
 * 字符串,轉字節數組,直接基於Files寫入文件
 * 
 * (注:我是直接用的BufferedWriter,比較方便)
 *
 * @param fileName
 * @param content
 * @throws IOException 
 */
private static void writeToFile(String fileName, String content) throws IOException{
	String[] lines = content.split("\r\n"); // 先把要寫入的字符串按行分割
	try( BufferedWriter output = new BufferedWriter(new FileWriter(fileName)); ) {
		for (String line: lines) {
			output.write(line); // 寫入一行(不含換行符)
			output.newLine(); // 寫入換行符
		}
		output.flush();
		System.out.println("數據寫入成功!文件位置:" + fileName);
	}
	System.out.println();
}

(3)基於基本IO複製文件

/**
 * 基於基本IO,以及字節數組緩衝區,複製文件
 * 打印顯示循環讀寫循環次數
 *
 * @param sourceFile
 * @param targetFile
 * @throws IOException 
 */
private static void copyByIO(String sourceFile, String targetFile) throws IOException {
	
	try( InputStream input = new FileInputStream(sourceFile);
	     OutputStream output = new FileOutputStream(targetFile); ){
		int size = 4;
		byte[] buffer = new byte[size]; // 字節數組緩衝區,大小爲size
		int len;
		int cnt = 0;
		while( (len = input.read(buffer)) != -1) {
			output.write(buffer, 0, len);
			cnt++;
		}
		System.out.println(sourceFile + " -> " + targetFile + " 複製成功!");
		System.out.println("字節數組緩衝區大小爲" + size + "時,讀寫循環次數爲" + cnt + "\n");
	}
}

(4)基於NIO複製文件

/**
 * 基於NIO,實現文件的複製
 *
 * @param sourceFile
 * @param targetFile
 * @throws IOException 
 */
private static void copyByNIO(String sourceFile, String targetFile) throws IOException {
	Path source = Paths.get(sourceFile);
	Path target = Paths.get(targetFile);
	Files.createDirectories(target.getParent());
	Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); // 如果輸出文件存在,則替換
	System.out.println(sourceFile + " -> " + targetFile + " 複製成功!\n");
}

(5)刪除文件

/**
 * 刪除文件
 *
 * @param fileName
 * @throws IOException 
 */
private static void deleteFile(String fileName) throws IOException {
	Path dir = Paths.get(fileName);
	Files.deleteIfExists(dir);
	System.out.println(fileName + " 刪除成功!\n");
}

(6)遞歸遍歷指定目錄下所有文件

/**
 * 遍歷打印指定目錄下全部目錄/文件名稱
 *
 * @param dir
 * @throws IOException 
 */
private static void walkDirectories(String dir) throws IOException {
	Path d = Paths.get(dir);
	Files.walk(d)
		//.sorted(Comparator.reverseOrder()) // 反向遍歷
		.forEach(System.out::println);
}

完整代碼

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Comparator;

public class IOTest {
    
	public static void main(String[] args) throws IOException {
        
		String fileName = "C:/example/from.txt";

        System.out.println("----- 創建文件 ------");
        createFile(fileName);

        System.out.println("-----  將字符串寫入文件 -------");
        // \r\n在txt文本中換行
        String str =
                "白日依山盡\r\n" +
                "黃河入海流\r\n" +
                "欲窮千里目\r\n" +
                "更上一層樓\r\n";
        writeToFile(fileName, str);

        System.out.println("--------- 基於基本IO流實現文件的複製 ----------");
        String toFile = "C:/example/to.txt";
        copyByIO(fileName, toFile);

        System.out.println("--------- 基於NIO實現文件的複製 ----------");
        String toFile2 = "C:/example/nio/to.txt";
        copyByNIO(fileName, toFile2);

        System.out.println("---------- 刪除指定文件 -------------");
        deleteFile(toFile);
        
        System.out.println("---------- 遍歷指定目錄文件 -------------");
        String dir = "C:/example";
        walkDirectories(dir);
    }

    /**
     * 基於指定文件名稱創建目錄及文件
     * 如果文件已經存在,則忽略
     *
     * @param fileName
     * @throws IOException 
     */
    private static void createFile(String fileName) throws IOException {
    	Path dir = Paths.get(fileName);
    	Files.createDirectories(dir.getParent());// 創建目錄,存在目錄也不會拋出異常
    	try{
    		Files.createFile(dir);// 創建文件,若文件已經存在則會拋出異常
    		System.out.println("創建文件成功!文件位置:" + fileName);
    	}
    	catch(FileAlreadyExistsException e) {
    		System.out.println("文件 " + fileName + " 已存在,無需創建!");
    	}
    	System.out.println();
    }

    /**
     * 提示:文件以字節操作,因此可以
     * 字符串,轉字節數組,直接基於Files寫入文件
     * 
     * (注:我是直接用的BufferedWriter,比較方便)
     *
     * @param fileName
     * @param content
     * @throws IOException 
     */
    private static void writeToFile(String fileName, String content) throws IOException{
    	String[] lines = content.split("\r\n"); // 先把要寫入的字符串按行分割
    	try( BufferedWriter output = new BufferedWriter(new FileWriter(fileName)); ) {
    		for (String line: lines) {
    			output.write(line); // 寫入一行(不含換行符)
    			output.newLine(); // 寫入換行符
    		}
    		output.flush();
    		System.out.println("數據寫入成功!文件位置:" + fileName);
    	}
    	System.out.println();
    }

    /**
     * 基於基本IO,以及字節數組緩衝區,複製文件
     * 打印顯示循環讀寫循環次數
     *
     * @param sourceFile
     * @param targetFile
     * @throws IOException 
     */
    private static void copyByIO(String sourceFile, String targetFile) throws IOException {
    	
    	try( InputStream input = new FileInputStream(sourceFile);
    	     OutputStream output = new FileOutputStream(targetFile); ){
    		int size = 4;
    		byte[] buffer = new byte[size]; // 字節數組緩衝區,大小爲size
    		int len;
    		int cnt = 0;
    		while( (len = input.read(buffer)) != -1) {
    			output.write(buffer, 0, len);
    			cnt++;
    		}
    		System.out.println(sourceFile + " -> " + targetFile + " 複製成功!");
    		System.out.println("字節數組緩衝區大小爲" + size + "時,讀寫循環次數爲" + cnt + "\n");
    	}
    }

    /**
     * 基於NIO,實現文件的複製
     *
     * @param sourceFile
     * @param targetFile
     * @throws IOException 
     */
    private static void copyByNIO(String sourceFile, String targetFile) throws IOException {
    	Path source = Paths.get(sourceFile);
    	Path target = Paths.get(targetFile);
    	Files.createDirectories(target.getParent());
    	Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); // 如果輸出文件存在,則替換
    	System.out.println(sourceFile + " -> " + targetFile + " 複製成功!\n");
    }

    /**
     * 刪除文件
     *
     * @param fileName
     * @throws IOException 
     */
    private static void deleteFile(String fileName) throws IOException {
    	Path dir = Paths.get(fileName);
    	Files.deleteIfExists(dir);
    	System.out.println(fileName + " 刪除成功!\n");
    }

    /**
     * 遍歷打印指定目錄下全部目錄/文件名稱
     *
     * @param dir
     * @throws IOException 
     */
    private static void walkDirectories(String dir) throws IOException {
    	Path d = Paths.get(dir);
    	Files.walk(d)
    		//.sorted(Comparator.reverseOrder()) // 反向遍歷
    		.forEach(System.out::println);
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章