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

运行结果:


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