1. 程式人生 > >Java檔案讀寫—utf-8格式

Java檔案讀寫—utf-8格式

 Windows預設檔案格式為UTF8格式,之前我們做過一個檔案讀寫,但寫入檔案的方式是二進位制格式,接下來,我們以windows預設的utf-8格式讀寫檔案。

IOStream類

package com.anson.java;

import java.io.*;

/**
 * 以windows預設UTF-8檔案格式讀寫檔案
 * @author anson
 *
 */
public class IOStream {

	private String path;
	
	public IOStream()
	{
		
	}
	public IOStream(String path)
	{
		this.path=path;
	}
	
	/**
	 * 
	 * utf-8windows預設檔案編碼格式寫入檔案
	 */
	
	public void WriteInfo()
	{
		try
		{
			File file=new File(path);
			FileOutputStream fileOutputStream=new FileOutputStream(file);
			OutputStreamWriter outputWriter=new OutputStreamWriter(fileOutputStream,"UTF-8");
			
			String[] str=new String[]{"string 1","string 2","string 3","string 4"};
			for(int i=0;i<str.length;i++)
			{
				outputWriter.append("\r\n"+str[i]);
			}
			outputWriter.close();
			fileOutputStream.close();
			
		}catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 讀出檔案資訊
	 */
	public void ReadInfo()
	{
		try
		{
			File file=new File(path);
			FileInputStream fileInputStream=new FileInputStream(file);
			InputStreamReader streamReader=new InputStreamReader(fileInputStream);
			StringBuffer strBuf=new StringBuffer();
			while(streamReader.ready())
			{
				strBuf.append((char)streamReader.read());
			}
			System.out.print(strBuf.toString());
			streamReader.close();
			fileInputStream.close();
		}catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
}

Test類

package com.anson.java;

import java.io.*;

public class Test {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{

    	IOStream ReaderWriter=new IOStream("/home/anson/桌面/3");
    	ReaderWriter.WriteInfo();
    	ReaderWriter.ReadInfo();
	}
}

執行結果: