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();
	}
}

運行結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章