为了简短起见,我正在尝试创建一个以参数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;
}
}
}
答案 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 :OutputStream
和File
类之间的差异:
OutputStream
:是一个接受输出字节并将它们发送到某个接收器的抽象类。File
:类是文件和目录路径名的抽象表示。