java两种方法写入文件


两种办法写入文件。
Two way for writing the files in java.

one,we don’t need to assgin the file’s encoding
一个不需要指定encode
another,we can assgin the file’s encoding before we write this file
一个需要指定。常见于写一个utf-8的文件

package com.javaer.examples.file;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
 
public class WritingFile {
	/**
	 * write something to a file,it will create a file if the file is not exist.
	 * 
	 * @param path
	 *            file path
	 * @param content
	 *            the content you want to write to the file
	 * @param isappend
	 *            true,will append the file.false,will rewrite the file
	 * @throws IOException
	 *             exception
	 */
	public static void appendFile(String path, String content, boolean isappend)
			throws IOException {
		File f = new File(path);
		if (!f.exists()) {
			f.createNewFile();
		}
		PrintWriter pw = new PrintWriter(new FileOutputStream(f, isappend));
		pw.print(content);
		pw.flush();
		pw.close();
	}
 
	/**
	 * create a file , and assgin the file's encode
	 * 
	 * @param path
	 *            file path
	 * @param content
	 *            the content you want to write to the file
	 * @param isappend
	 *            true,will append the file.false,will rewrite the file
	 * @param encode
	 *            file's encode
	 * @throws IOException
	 *            exception
	 */
	public static void appendFile(String path, String content,
			boolean isappend, String encode) throws IOException {
		File f = new File(path);
 
		if (!f.exists()) {
			f.createNewFile();
		}
		OutputStreamWriter isw = new OutputStreamWriter(new FileOutputStream(f,
				isappend), encode);
		isw.write(content);
		isw.flush();
		isw.close();
	}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			WritingFile.appendFile("/x.txt", "what is your name", false);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
		try {
			WritingFile.appendFile("/x2.txt", "what is your name", false,"UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
	}
 
}
如果你是一名技术人员可加我QQ 2651-0442-02,如果你是java技术人还可以加入QQ群 1784-9136-0
你将得到的不仅仅是技术的交流,还有职业机会,人生解惑.
首发地址:月小升博客http://java-er.com/blog/java-write-file/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
此条目发表在 JAVA 分类目录,贴了 , 标签。将固定链接加入收藏夹。
既然来了,就评论一下,不会怀孕的

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">