我正在创建一个名为 jfv.properties 的文件,我想将一个简单的字符串写入该文件。在此文件正在创建,字符串未打印。下面的代码有问题吗?我在 Debug模式下运行,没有抛出任何异常。
File file = new File(filePath,"jfv.properties");
FileOutputStream fo = null;
try {
fo = new FileOutputStream(file);
PrintWriter p = new PrintWriter(fo);
p.println("some string");
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (SecurityException s){
s.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(fo != null ){
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
PrintWriter
未刷新。使用
p.println("some string");
p.flush();
或使用autoFlush
PrintWriter p = new PrintWriter(fo, true);
p.println("some string");
或者只是关闭
它。
autoFlush
适用于 println
、printf
和 format
。查看 PrintWriter 的 javadoc .
详情
PrintWriter
可以用另一个Writer
、File
或文件名或OutputStream
构造。如果使用 OutputStream
实例化它,javadoc 说:
public PrintWriter(OutputStream out)
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.
和 OutputStreamWriter 的 javadoc说:
... The resulting bytes are accumulated in a buffer before being written to the underlying output stream. ...
编辑
所以你的代码
fo = new FileOutputStream(file);
PrintWriter p = new PrintWriter(fo);
会导致这个流模型
+-------------+ +--------------------+ +------------------+
| PrintWriter | --------> | OutputStreamWriter | -------> | FileOutputStream |
+-------------+ +--------------------+ +------------------+
因此 println
不会直接将字符串写入 FileOutputStream
p.println("some string")
+-> outputStreamWriter.write("some string")
+--> write to internal buffer (as bytes)
p.flush();
+-> outputStreamWriter.flush();
+--> internal buffer flush
+--> fileOutputStream.write(bytes)
关于java - 没有字符串打印到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27009429/