java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

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

	}

}


This entry was posted in JAVA and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-write-file/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply