我正在尝试使用 PrintWriter.java, 但是却遇到了一个很奇怪的问题,我无法弄清楚我在这里缺少什么。
MyPrintWriter.java
public class MyPrintWriter { public static void main(String[] args) { File myFile = new File("myFileDirectory/myFileName.txt"); try { FileWriter fw = new FileWriter(myFile); PrintWriter pw = new PrintWriter(fw); pw.println("Hello World!"); pw.close(); } catch (FileNotFoundException e) { System.err.println("File not found: " + myFile); } catch (Exception e) { e.printStackTrace(); } } }
MyFileWriter.java
public class MyFileWriter { public static void main(String[] args) { File myFile = new File("myFileDirectory/myFileName.txt"); try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); FileWriter fw = new FileWriter(myFile); PrintWriter pw = new PrintWriter(fw); String input; input = br.readLine(); while(input != null) { pw.println(input); input = br.readLine(); } br.close(); pw.close(); } catch (FileNotFoundException e) { System.err.println("File not found: " + myFile); } catch (Exception e) { e.printStackTrace(); } } }
MyPrintWriter.java 很高兴写入 myFileName.txt 文件,但 MyFileWrite.java 不能。
有人可以帮助我了解我在这里想念的东西吗?
您可能需要冲洗印刷机。
PrintWriter具有FileWriter参数的构造函数将创建一个PrintWriter并将其autoFlush设置为off
PrintWriter
FileWriter
autoFlush
pw.flush()之前致电pw.close();应该可以解决问题
pw.flush()
pw.close();