三点水不是水 2019-12-20 20:44 采纳率: 100%
浏览 198
已采纳

如何从键盘输入一系列字符,保存在文件里,最终显示在屏幕上

从键盘终端依次输入
a
b
c
d
e
然后要在屏幕上看到
a
b
c
d
e
这样的输出

public static void main(String[] args) {
        File f=new File("f:"+File.separator+"abc.txt");
        try {
            OutputStream fout=new FileOutputStream(f);
            OutputStream out=System.out;
            Scanner scan=new Scanner(System.in);
            PrintStream ps=new PrintStream(fout);
            String content;
            while(true){
                content=scan.nextLine();
                ps.print(content);
                if(content==null){
                    break;
                }
                //out.write(content.getBytes());
            }
            out.write(content.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


我目前出现的问题是不能在输入完所有的字母之后,一次性的在屏幕上显示
a
b
c
d
e
这样的输出。只是输入一个a屏幕上就输出一个a
希望有大佬看到后,帮忙想想解决办法,谢谢啦

  • 写回答

1条回答 默认 最新

  • 「已注销」 2019-12-23 11:57
    关注

    限定条件根据需求改

    public static void main(String[] args) {
            File f=new File("i:"+File.separator+"abc.txt");
            try {
                OutputStream fout=new FileOutputStream(f);
                OutputStream out=System.out;
                Scanner scan=new Scanner(System.in);
                PrintStream ps=new PrintStream(fout);
                String content = "";
                StringBuffer printContent = new StringBuffer();
                int i = 0;
                while(i<5){
                    i++;
                    content=scan.nextLine();
                    printContent.append(content+"\r\n");
                    ps.print(content);
                    if(content==null){
                        break;
                    }
                    //out.write(content.getBytes());
                }
                out.write(printContent.toString().getBytes());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了