我正在创建一个名为jfv.properties的文件,我想在文件中写一个简单的字符串。在这个文件被创建,字符串没有被打印。以下代码有问题吗?我已经在调试模式下运行,没有抛出异常。
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();
}
}
}
答案 0 :(得分:1)
如果您在p.close()
finally
,那就更好了
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();
} finally {
p.close();
if(fo != null ){
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 1 :(得分:1)
File file = new File(filePath, "jfv.properties");
FileOutputStream fo = null;
BufferedWriter bw = null;
FileWriter fw = null;
try {
fo = new FileOutputStream(file);
PrintWriter p = new PrintWriter(fo);
p.println("some string");
//change it
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
bw.write("some string");
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SecurityException s) {
s.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fo != null) {
fo.close();
}
if (fw != null) {
fw.close();
}
if (bw != null) {
bw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 2 :(得分:1)
PrintWriter
未刷新。使用
p.println("some string");
p.flush();
或使用autoFlush
PrintWriter p = new PrintWriter(fo, true);
p.println("some string");
或只是close
。
autoFlush
适用于println
,printf
和format
。请参阅PrintWriter的javadoc。
<强>详情
PrintWriter
可以使用其他Writer
,File
或文件名或OutputStream
构建。如果使用OutputStream
实例化它,javadoc会说:
public PrintWriter(OutputStream out)
从现有的OutputStream创建一个没有自动行刷新的新PrintWriter。这个便利构造函数创建了必要的中间 OutputStreamWriter ,它将使用默认的字符编码将字符转换为字节。
和OutputStreamWriter的javadoc说:
...在写入底层输出流之前,生成的字节在缓冲区中累积。 ...
修改强>
所以你的代码
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)