在java中打开临时文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/876816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:32:11  来源:igfitidea点击:

open temp file in java

javaio

提问by

I'm writing string to temporary file (temp.txt) and I want that file should open after clicking button of my awt window it should delete when I close that file (after opening that file), how can I do this?

我正在将字符串写入临时文件 ( temp.txt) 并且我希望该文件应该在单击我的 awt 窗口的按钮后打开它应该在我关闭该文件时删除它(打开该文件后),我该怎么做?

This is the code that I have been using to create temporary file in Java:

这是我用来在 Java 中创建临时文件的代码:

File temp = File.createTempFile("temp",".txt");

FileWriter fileoutput = new FileWriter(temp);
Bufferedwriter buffout = new BufferedWriter(fileoutput);

回答by Bombe

回答by pgras

A file created by:

创建的文件:

File temp = File.createTempFile("temp",".txt");

Will not be deleted, see javadoc, you have to call

不会被删除,看javadoc,你要调用

temp.deleteOnExit();

so the JVM will delete the file on exit...

所以JVM会在退出时删除文件......

回答by Harry Lime

How about something like:

怎么样:

if (!temp.delete())
{
    // wasn't deleted for some reason, delete on exit instead
    temp.deleteOnExit();
}

回答by Tom Hawtin - tackline

To perform an operation when clicking a button, you will need code something like this:

要在单击按钮时执行操作,您将需要如下代码:

    button.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(ActionEvent event) {
            fileOperation();
        }
    }
...
private void fileOperation() {
    ... do stuff with file ...
}

You can probably find many examples with google. Generally the anonymous inner class code should be short and just translate the event and context into operations meaningful to the outer class.

你可能可以用谷歌找到很多例子。通常匿名内部类代码应该很短,只是将事件和上下文转换为对外部类有意义的操作。

Currently you need to delete the file manually with File.deleteafter you have closed it. If you really wanted to you could extends, say, RandomAccessFileand override closeto delete after the close. I believe delete-on-close was considered as a mode for opening file on JDK7 (no idea if it is in or not).

目前,您需要File.delete在关闭文件后手动删除该文件。如果你真的想要,你可以在关闭后扩展,说RandomAccessFile和覆盖close删除。我相信关闭时删除被认为是在 JDK7 上打开文件的一种模式(不知道它是否在里面)。

Just writing to a file, as in your code, would be pointless. You would presumably want to delete the file after closing a read stream no the write stream. It's not a bad idea to avoid temporary files if you possibly can.

仅写入文件(如您的代码)将毫无意义。您可能希望在关闭读取流后删除文件,而不是写入流。如果可能的话,避免使用临时文件并不是一个坏主意。