我遇到了PrintWriter
的一些问题。我写了一些代码,它们只是从文件中获取一些输入,然后将其输出到另一个。
尽管已创建文件,但该文件仍为空。所需的输入可以轻松地在控制台中打印出来,这意味着FileInputStream正常工作。
为什么PrintWriter不打印任何内容?
public static void writeInFile(File in, File out) throws FileNotFoundException {
PrintWriter outputStream = null
Scanner scanner = new Scanner(new FileInputStream(in));
outputStream = new PrintWriter(new FileOutputStream(out));
outputStream.print("test");
while(scanner.hasNext()) {
outputStream.print(scanner.nextLine() + "\n");
}
scanner.close();
}
答案 0 :(得分:2)
确保始终关闭OutputStreams
:
while(scanner.hasNext()) {
String s = scanner.nextLine();
outputStream.print(s+"\n");
System.out.println("Test "+s); //d.h. das Problem liegt am outputstream
}
outputStream.close();
scanner.close();
编辑:当您close
outputStream时,它会自动调用flush
,这会将缓冲区写入文件。如果不关闭它,缓冲区可能永远不会被清空/写入文件,就像这里一样。
另请参阅this answer。
答案 1 :(得分:0)
在处理需要清理的IO时,我更喜欢使用自动资源清理。这是最基本的需求:
public static void writeInToOut(InputStream in, OutputStream out) {
try(PrintWriter outputStream = new PrintWriter(out);
Scanner scanner = new Scanner(in)) {
while(scanner.hasNext()) {
outputStream.print(scanner.nextLine()+"\n");
}
}
}
您现在可以通过几种方式重载此功能:
public static void writeInToOut(File file, OutputStream out) {
try (InputStream in = new FileInputStream(file)) {
writeInToOut(in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
public static void writeInToOut(File inFile, File outFile) {
try (InputStream in = new FileInputStream(inFile);
OutputStream out = new FileOutputStream(outFile)) {
writeInToOut(in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
public static void writeStdInToFile(File file) {
try (OutputStream out = new FileOutputStream(file)) {
writeInToOut(System.in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}