Java學習筆記——利用通道寫文件

利用Java中的java.nio.channels.WritableByteChannel的方法來實現寫文件,通過通道可以設定通道的使用方式,從而決定寫文件的方式。具體實現代碼如下:

import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.io.*;
import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.util.*;
public class WriteProverbs {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自動生成方法存根
		String[] sayings = {"Teacher: Kids,what does the chicken give you?",
				"Student: Meat!",
				"Teacher: Very good! Now what does the pig give you?",
				"Student: Bacon!",
				"Teacher: Great! And what does the fat cow give you?",
				"Student: Homework!" };
		Path file = Paths.get(System.getProperty("user.home")).resolve(
				"Beginning Java Stuff").resolve("Proverbs.txt");
		try {
			Files.createDirectories(file.getParent());

		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
		int maxLength=0;
		for(String saying:sayings){
			if(maxLength<saying.length())
			{
				maxLength=saying.length();
			}
		}
		ByteBuffer buf=ByteBuffer.allocate(1024);//分配的空間一定要大於字符串字長
		try{
			WritableByteChannel channel=Files.newByteChannel(file,EnumSet.of(CREATE,WRITE,APPEND));//EnumSet是設定通道的使用方式,APPEND是在原有的內容後面寫
			
			for(String saying:sayings){
				buf.put(saying.getBytes());
				buf.flip();
				
				channel.write(buf);
				buf.clear();
			}
			System.out.println("Proverbs written to file.");
			
		}catch(IOException e){
			e.printStackTrace();
		}
	}

}
使用APPEND實現結果如下:




發佈了45 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章