文件流的读与写

文件流的读取有很方法,下面介绍一种文件读与写的方法。
读某一路径下的文件,我们可以用:FileReader和BufferedReader组合,采用一行一行的读取办法,如
public String readFile(File file) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuffer sbf = new StringBuffer("");
		String line = null;
		while ((line = br.readLine()) != null) {
			sbf.append(line).append("\r\n");// 按行读取,追加换行\r\n
		}
		br.close();
		return sbf.toString();
	}

将读取到的文件写到某一路径下:我们可以结合FileWriter和BufferedWriter,如
public void writeFile(String str, String savePath) throws Exception {
		BufferedWriter bw = new BufferedWriter(new FileWriter(savePath));
		bw.write(str);
		bw.close();
	}

最后,记得流用完后一定要记得关闭流,不然会出各种问题的
下面给出一个实例,以供参考:
package qjb;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

/****************
 * 文件读取与保存
 * 
 * @author Administrator
 * 
 ****************/
public class ReaderFile {
	/**
	 * 根据路径读取文件
	 * 
	 * @param readPath
	 *            读取文件的路径
	 * @return
	 * @throws Exception
	 */
	public String readFile(String readPath) throws Exception {
		return readFile(new File(readPath));
	}

	/**
	 * 读取文件
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public String readFile(File file) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuffer sbf = new StringBuffer("");
		String line = null;
		while ((line = br.readLine()) != null) {
			sbf.append(line).append("\r\n");// 按行读取,追加换行\r\n
		}
		br.close();
		return sbf.toString();
	}

	/**
	 * 写入文件
	 * 
	 * @param str
	 *            要保存的内容
	 * @param savePath
	 *            保存的文件路径
	 * @throws Exception
	 *             找不到路径
	 */
	public void writeFile(String str, String savePath) throws Exception {
		BufferedWriter bw = new BufferedWriter(new FileWriter(savePath));
		bw.write(str);
		bw.close();
	}

	public static void main(String[] args) {
		ReaderFile fop = new ReaderFile();
		String filePath = "src/qjb/abc.txt";
		String str = null;
		try {
			str = fop.readFile(filePath);
			System.out.println(str);
		} catch (Exception e) {
			System.out.println("文件不存在");
		}
		String savePath = "src/qjb/def.txt";// 将上一个读取的文件另存一份
		try {
			fop.writeFile(str, savePath);
		} catch (Exception e) {
			System.out.println("保存文件失败(路径错误)");
		}
	}
}

谢谢!

你可能感兴趣的:(java、文件流读写学习)