将控制台输入的每一行字符串,输出至txt文件当中

/**
 *    需求:将控制台输入的每一行字符串,输出至txt文件当中.
/**
 *    需求:将控制台输入的每一行字符串,输出至txt文件当中.
 *    思路:
 *    1.首先想到BufferReader高级流读取一行字符串readLine方法.
 *    2.但是前提依赖于字符转换流ISR和低级节点流,这里是从控制台输入,节点流自然是System.in.如果是从文件输入,则节点流换成FIS即可
 *    3.这样就能建立一条输入流了.BufferedReader(new InputStreamReader(System.in))
 *    4.然后用输入流进来的字符,通过PrintWriter输出至对应的txt文件中.注意:PrintWriter同样依赖于节点流(这里是写入文件用,FOS流)和字符转换流
 *    (OSW,将字符转换成字节写入文件).
 */
public class ConsleToFile {

    public static void main(String[] args)  {
        /*建立测试文件夹及文件对象*/
        File dir = new File("."+File.separator+"src"+File.separator+"practise"+File.separator+"io");
        if(!dir.exists()){
            dir.mkdir();
        }

        File file = new File(dir,"note.txt");

        /*1.字符输出到控制台,需要用到BufferedReader*/
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        PrintWriter out = null;
        try {
            out = new PrintWriter(file);
        } catch (FileNotFoundException e) {
            System.out.println("目标文件不存在");
            e.printStackTrace();
        }

        System.out.println("请输入输出至note.txt中的语句");
        /*2.建立循环*/
        while(true){
            String line = null;
            try {
                line = in.readLine();
            } catch (IOException e) {
                //未知IO异常
                e.printStackTrace();
            }

            /*定义退出循环条件*/
            if("exit".equals(line)){
                break;
            }
            /*输出语句*/
            out.println(line);
        }
        /*关闭资源*/
        try {
            if(in != null)
                in.close();
            if(out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
View Code

需求如果是从控制台输入一行字符,输出至控制台,则将PrintWriter依赖的低级节点流换成System.out即可

 

转载于:https://www.cnblogs.com/zyjcxc/p/5467162.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值