我确信这个问题有一个相当简单的答案,所以我们走了。
我正在尝试使用FileWriter将文本写入文件。我的程序从用户指定的现有文件中读取文本,然后询问是将文本打印到控制台还是打印到新文件,也是由用户命名。
我相信我的问题是将FileWriter传递给“FileOrConsole”方法。我没有正确地在“FileOrConsole”方法中传递或声明FileWriter吗?始终会创建该文件,但不会写入任何内容。
以下是代码:
import java.io.*;
import java.util.*;
public class Reader {
public static void main(String[] args) throws IOException {
Scanner s = null, input = new Scanner(System.in);
BufferedWriter out = null;
try {
System.out.println("Would you like to read from a file?");
String answer = input.nextLine();
while (answer.startsWith("y")) {
System.out.println("What file would you like to read from?");
String file = input.nextLine();
s = new Scanner(new BufferedReader(new FileReader(file)));
System.out
.println("Would you like to print file output to console or file?");
FileOrConsole(input.nextLine(), s, input, out);
System.out
.println("\nWould you like to read from the file again?");
answer = input.nextLine();
}
if (!answer.equalsIgnoreCase("yes")) {
System.out.println("Goodbye!");
}
} catch (IOException e) {
System.out.println("ERROR! File not found!");
// e.printStackTrace();
} finally {
if (s != null) {
s.close();
}
if (out != null) {
out.close();
}
}
}
public static void FileOrConsole(String response, Scanner s, Scanner input,
BufferedWriter out) {
if (response.equalsIgnoreCase("console")) {
while (s.hasNext()) {
System.out.println(s.nextLine());
}
} else if (response.equalsIgnoreCase("file")) {
System.out.println("Name of output file?");
response = input.nextLine();
try {
out = new BufferedWriter(new FileWriter(response));
} catch (IOException e) {
e.printStackTrace();
}
while (s.hasNext()) {
try {
out.write(s.nextLine());
out.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Sorry, invalid response. File or console?");
response = input.nextLine();
FileOrConsole(response, s, input, out);
}
}
}
答案 0 :(得分:4)
你犯了经典错误,忘记了在java的情况下通过值传递的参数它是引用的值。问题在于你的作业
out = new BufferedWriter(new FileWriter(response));
实际上不会更改main()中声明的变量,它保持为空
BufferedWriter out = null; 然后在最后它跳过if(out == null)的close() 因为它是缓冲而你没有刷新没有写入文件。 你要做的是out.close();在FileOrConsole方法调用
中OR
执行out = new BufferedWriter(new FileWriter(response)); 在它之外。你选择:-)
答案 1 :(得分:0)
尝试刷新您的信息流,但更重要的是,请记得关闭它。
以下是处理流的推荐做法的代码示例。同样的方法也可以用于输入流和数据库代码之类的东西,重要的是总是在自己之后清理以获得预期的结果。
BufferedWriter out = null;
try {
out = // ... create your writer
// ... use your writer
} catch(IOException ex) {
// maybe there was a problem creating or using the writer
} finally {
if (null != out) {
out.flush();
out.close();
out = null;
}
}