java读写文件

package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileReadUtil {
	
	/**
	 * 读文件
	 * @param path 文件路径
	 */
	public static void readFile(String path) throws Exception
	{
		File file = new File(path);
		BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		String line = "";
		while((line = bf.readLine()) != null)
		{
			System.out.println(line);
		}
		bf.close();
	}
	
	/**
	 * 
	 * @param content 写入的内容
	 * @param path 文件路径
	 * @param append 文件内容是否为追加
	 * @throws Exception
	 */
	public static void writeFile(String content, String path, boolean append) throws Exception
	{
		File file = new File(path);
		
		OutputStreamWriter pw = new OutputStreamWriter(new FileOutputStream(file, append));
		pw.write(content);
		pw.close();
	}
	
	public static void main(String[] args) throws Exception {
		
		writeFile("123", "F:/123.txt", true);
		
		readFile("F:/123.txt");
	}
}
 

 

你可能感兴趣的:(java)