java - 没有字符串打印到文件中

标签 java file fileoutputstream

我正在创建一个名为 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 适用于 printlnprintfformat。查看 PrintWriter 的 javadoc .

详情

PrintWriter 可以用另一个WriterFile 或文件名或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/

相关文章:

java - 设置 JComboBox 的背景?

在 C 中使用多线程服务器时无法完成文件传输

java - 将文件读取到字符串数组并显示每条记录

Java 向文件写入字节和从文件读取字节

java - 匹配 XText 中的字符串,无论大小写

java - 这是创建包含多个包的 jar 文件的正确方法吗?

java - 如何自动写入和读取文件?

java - FileOutputStream 访问被拒绝 : JAVA

java - 编码 URL 查询参数

python - 如何从文件中读取 float ?