赞
踩
通过代码创建一个文件a.txt
然后写一个方法,控制台循环输入内容,然后通过gbk的编码格式保存到
a.txt中(要求可以追加),直到输入exit结束
再写一个方法,要求用字符缓冲流读取a.txt中的内容到控制台打印出来
package com.Work1; import org.junit.Test; import java.io.*; import java.util.Scanner; /** * @Author: 廾匸 * @Date: 2020/12/4 18:24 * @Description: * @version: 1.01 */ public class Dome { @Test public void test01() throws IOException { File file = new File("G:/作业/a.txt"); file.createNewFile(); input(file); show(file); } public static void input(File file) throws IOException { while (true) { Scanner in = new Scanner(System.in); System.out.println("请输入:"); String str = in.nextLine(); if (str.equals("exit")) { break; } OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file, true), "gbk"); writer.write(str + "\n"); writer.flush(); } } public void show(File file) throws IOException { if(!file.exists()){ return; } InputStream input = new BufferedInputStream(new FileInputStream(file)); InputStreamReader reader = new InputStreamReader(input,"gbk"); int len; while((len = reader.read()) != -1){ System.out.print((char)len); } reader.close(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。