Java实验5 IO流第一题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42623428/article/details/84593031

编写程序,要求:用户在键盘每输入一行文本,程序将这段文本显示在控制台中。当用户输入的一行文本是“exit”(不区分大小写)时,程序将用户所有输入的文本都写入到文件log.txt中,并退出。(要求:控制台输入通过流封装System.in获取,不要使用Scanner) 

import java.io.*;
public class Main {

	public static void main(String[] args) {
		BufferedReader in = null;
		BufferedWriter out = null;
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("log.txt")));
			String s;
			while ((s = in.readLine()) != null) {
				if (s.equals("exit") || s.equals("EXIT")) {
					break;
				}
                                System.out.println(s);
				out.write(s);
				out.newLine();
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42623428/article/details/84593031