使用方法输出到用户决定的文本文件

时间:2016-03-08 18:59:36

标签: java file-io io text-files

为了简短起见,我正在尝试创建一个以参数a为参数的方法 输出文件流名称,然后允许用户写入该文本,并使用while循环追加到它。这是我写的:

public void insertRowsToFile(OutputStream output) throws IOException {

    Scanner keyboard = new Scanner(System.in);
    //here is my mistake that i dont know how to solve (outputstream, boolean is undefined)
    PrintWriter out = new PrintWriter(
                          new OutputStreamWriter(
                              new FileOutputStream(output, true))); 
    boolean answer = true;
    while (answer == true) {
        System.out.println("Enter the row:");
        String entered = keyboard.nextLine();
        out.println(entered);
        System.out.println("Would you like to write more? (yes to continue)");
        String answer2 = keyboard.next();
        if (!answer2.equals("yes"))
            answer = false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的output变量应为File而不是OutputStream

请记住,FileOutputStream的构造函数仅在以下情况下合法:

  • new FileOutputStream(File, boolean)
  • new FileOutputStream(String, boolean)

这是正确的方法声明:

public void insertRowsToFile(File output) throws IOException {
    ...
}

编辑,未经测试:或者更好的方法是将OutputStream作为参数,但更改out变量的初始化:

public void insertRowsToFile(OutputStream output) throws IOException { 
    ...
    PrintWriter out = new PrintWriter(new OutputStreamWriter(output)); 
    ...
}

修改2 OutputStreamFile类之间的差异:

  • OutputStream:是一个接受输出字节并将它们发送到某个接收器的抽象类。
  • File:类是文件和目录路径名的抽象表示。

来自:TutorialsPoint.com