2013-01-06 99 views
3

今天,当我正在处理某种类型的servlet,它正在向我的硬盘上的某个文件写入一些信息时,我正在使用以下代码来执行写入操作关于close方法()用于关闭流

File f=new File("c:/users/dell/desktop/ja/MyLOgs.txt"); 
     PrintWriter out=new PrintWriter(new FileWriter(f,true)); 
     out.println("the name of the user is "+name+"\n"); 
     out.println("the email of the user is "+ email+"\n"); 
     out.close();    //**my question is about this statement** 

当我不使用的语句时,servlet被编译好了,但它并没有任何内容写入文件,但是当我把它,然后成功地进行写操作。我的问题是:

  1. 为什么数据没有写入文件,当我不包括该语句(即使我的servlet没有任何错误编译)?
  2. 关闭操作在多大程度上对于流是相当大的?
+1

你应该在'finally'块 – MrSmith42

回答

4

调用close()导致所有数据被刷新。您已经构建了PrintWriter而未启用自动刷新(对构造函数之一的第二个参数),这意味着您将不得不手动调用flush(),该函数为您提供了close()的帮助。

关闭还释放打开文件时使用的任何系统资源。尽管虚拟机和操作系统最终会关闭该文件,但最好在完成该操作后关闭该文件以节省计算机上的内存。

您也可以将close()放在finally区块内,以确保总是被调用。如:

PrintWriter out = null; 
try { 
    File f = new File("c:/users/dell/desktop/ja/MyLOgs.txt"); 
    out = new PrintWriter(new FileWriter(f,true)); 
    out.println("the name of the user is "+name+"\n"); 
    out.println("the email of the user is "+ email+"\n"); 
} finally { 
    out.close(); 
} 

参见:PrintWriter

Sanchit也使得有关获取Java VM 7自动关闭你的流你不会自动需要他们的时刻好点。

+0

中调用'close()'那么输入流是什么呢,它们是否也需要关闭它们? – nobalG

+0

是的,您还应该使用相同的'close()'方法关闭'InputStream's。不再需要关闭任何“可关闭”的东西是一种好习惯。 (http://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html) –

2

这是因为PrintWriter会缓存您的数据,以便每次写入操作都不会重复执行I/O操作(这非常昂贵)。当你打电话给close()时,缓冲区会被冲入文件。您也可以拨打flush()强制写入数据而不关闭流。

3

当你close a PrintWriter,它会将其所有数据刷新到任何你想要的数据去。它不会自动执行此操作,因为如果每次写信给某事时都会这样做,因为写作不是一个简单的过程,所以效率会很低。

您可以使用flush();实现同样的效果,但您应该始终关闭流 - 请参阅此处:http://www.javapractices.com/topic/TopicAction.do?Id=8和此处:http://docs.oracle.com/javase/tutorial/jndi/ldap/close.html。当您完成使用时,请始终致电close();。此外,为了确保它是无论总是关闭例外,你可以这样做:

try { 
    //do stuff 
} finally { 
    outputStream.close(): 
} 
1

PrintWriter缓冲要写入的数据,直到缓冲区满时才写入磁盘。调用close()将确保剩余的数据被刷新以及关闭OutputStream

close()陈述通常出现在finally块中。

2

流在关闭之前自动刷新其数据。因此,您可以使用out.flush();每隔一段时间手动刷新一次数据,或者您可以在完成后关闭该数据流。当程序结束时,流关闭并且数据被刷新,这就是为什么大多数时候人们不关闭它们的流!

使用Java 7,您可以执行下面的操作,它将按照您打开它们的顺序自动关闭您的流。

public static void main(String[] args) { 
    String name = ""; 
    String email = ""; 
    File f = new File("c:/users/dell/desktop/ja/MyLOgs.txt"); 
    try (FileWriter fw = new FileWriter(f, true); PrintWriter out = new PrintWriter(fw);) { 
    out.println("the name of the user is " + name + "\n"); 
    out.println("the email of the user is " + email + "\n"); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 
0

为什么当我不包含该语句时数据没有写入文件?

当进程终止时,非托管资源将被释放。对于InputStreams这很好。对于OutputStreams,您可能会丢失缓冲的数据,所以您应该至少在退出程序之前刷新流。

+0

@Tom Leese:那是什么? – nobalG