BufferedReader类和BufferedWriter类

由键盘输入多行字符并写入指定文件中,以end字符串结束

1.效果图

BufferedReader类和BufferedWriter类_第1张图片
BufferedReader类和BufferedWriter类_第2张图片

2. Java代码

package com.example.demo.stream;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import com.example.demo.file.FileTest;

/**
 * @Description BufferedReader类和BufferedWriter类
 * @author 大都督
 * @date 2018年12月25日
 */
public class BufferedReaderAndBufferedWriterTest {

	public static void main(String[] args) throws IOException {
		File file = FileTest.createFile(FileTest.parent, "b_r_w.txt");
		//由键盘输入多行字符并写入指定文件中,以end字符串结束
		keyboardInputOnFile(file);
	}

	/** 
	* @Title: keyboardInputOnFile 
	* @Description:  由键盘输入多行字符并写入指定文件中,以end字符串结束
	* @param file 
	* @author 大都督
	* @date 2018年12月25日
	* @return void
	 * @throws IOException 
	*/
	private static void keyboardInputOnFile(File file) throws IOException {
		System.out.println("请输入内容:");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
		String line = null;
		try {
			while (!(line = bufferedReader.readLine()).equals("end")) {
				bufferedWriter.write(line);
				bufferedWriter.newLine();
			}
			bufferedReader.close();
			bufferedWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(java,Java)