`

java文件写操作

阅读更多
package com.test2;

import java.io.*;

/**
 * @desc  java文件写操作
 * @author zhaozhi3758
 *
 */
public class FileWriteT {
	//以下各方法文件会自动创建
	public void writeToFile1(String path,String str) throws FileNotFoundException{
		PrintWriter pw = new PrintWriter(new FileOutputStream(path));
        pw.println(str);
        pw.flush();
        pw.close();
	}
	
	public void writeToFile2(String path,String str) throws IOException{
		FileOutputStream pw = new FileOutputStream(path);//以覆盖的方式
		//FileOutputStream pw = new FileOutputStream(path,true);//以追加的方式
		byte abyte[] = str.getBytes();
		pw.write(abyte);
        pw.flush();
        pw.close();
	}
	
	public void writeToFile3(String path,String str) throws IOException{
		    BufferedWriter bwrite = new BufferedWriter(new FileWriter(path,true));//去掉true,非追加   
		    //BufferedWriter bwrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path,true)));//OutputStreamWriter 是字符流通向字节流的桥梁,用BufferedWriter再次封装是为了提高效率
			bwrite.write(str);
			bwrite.flush();
			bwrite.close();
	}
	public static void main(String[] args) throws IOException {
		
		FileWriteT ft=new FileWriteT();
		ft.writeToFile3("f:/login.properties","哈哈==sdasd"+"\n"+"#dddd"+"\n");//此种文件加换行符是换行的,但txt格式不行
		
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics