码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-06 21:52:36      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

/**
 *    需求:将控制台输入的每一行字符串,输出至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即可

 

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

标签:

原文地址:http://www.cnblogs.com/zyjcxc/p/5467162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!