写入文件的问题

0 java

我在写文件时遇到问题:

FileInputStream fin;              
try
{
    fin = new FileInputStream ("c:/text.txt");     
    PrintStream p = new PrintStream(fin);
    p.println ("test");
    fin.close();               
}
catch (IOException ioe)
{
    System.err.println (ioe.getMessage);
}
Run Code Online (Sandbox Code Playgroud)

这段代码有问题吗?

小智 6

你需要使用一个FileOutputStream.


cle*_*tus 5

习惯以下结构.你会在Java中使用它很多.

PrintStream out = null;
try {
  out = new PrintStream(new FileOutputStream("c:/text.txt"));
  out.println ("test");
} catch (IOException e) {
  System.err.println (e.getMessage);
} finally {
  if (out != null) {
    try { out.close(): } catch (Exception e) { }
  }
  out = null; // safe but not strictly necessary unless you reuse fin in the same scope
}
Run Code Online (Sandbox Code Playgroud)

至少直到ARM阻止 Java 7中的最终结果.

如上所述,你应该关闭PrintStream而不是FileOutputStream这样,以上是一个更好的使用形式.