【问题标题】:Read from Console and write to file with stdio从控制台读取并使用 stdio 写入文件
【发布时间】:2015-10-27 14:17:43
【问题描述】:

我有这个从控制台读取和写入的代码 sn-p。我想覆盖while循环,以便将输出写入本地保存在我的电脑上的.txt文件,而不是写入控制台。 我已经搜索并找到了一种将 System.out 重定向到 OutputStream(?) 的方法,但问题是我希望在控制台上显示已执行对文件的写入/输出的确认。一旦我重定向 System.out,我使用 System.out 输出的所有其他内容也会被重定向(?) 你们能帮帮我吗?

 class Echo {

  public static void main (String [] args) throws java.io.IOException {
    int ch;
    System.out.print ("Enter some text: ");
    while ((ch = System.in.read ()) != '\n') {
      System.out.print ((char) ch);
    }
    System.out.println("Zugriff aufgezeichnet");
  }
 }

【问题讨论】:

    标签: java stdio


    【解决方案1】:

    您可以使用FileWriter 写入文件而不是写入终端。 确保你在完成文件后flushclose 文件。

    class Echo {
    
      public static void main (String [] args) throws java.io.IOException {
        int ch;
        System.out.print ("Enter some text: ");
        FileWrite fw=new FileWriter(new File("fileName.txt"));
        while ((ch = System.in.read ()) != '\n') {
          fw.write((char) ch + "");
        }
        System.out.println("Zugriff aufgezeichnet");
        fw.flush();
        fw.close();
      }
     }
    

    【讨论】:

    • 谢谢哥们。即使你的工作正常,没有时间的答案也会更优雅。
    【解决方案2】:

    使用Scanner 获取输入

    你不需要一个while循环,我认为这是更好的方法 输出在 FileWriter 的另一个答案中进行了解释

    我把它和nafas的代码混在一起了:

    class Echo {
    
      public static void main (String [] args) throws java.io.IOException {
    
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter some text: ");
        String input = sc.nextLine();
        System.out.println("Zugriff aufgezeichnet");
    
        FileWrite fw=new FileWriter(new File("fileName.txt"));
        fw.write(input);
        fw.flush();
        fw.close();
      }
     }
    

    【讨论】:

    • 谢谢。 Nafas 的答案也可以,但这既简单又优雅。
    猜你喜欢
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2021-11-10
    相关资源
    最近更新 更多