Trouble in java.io.File.DeleteONExit()

//at my servlet
String prjTmpPath= request.getRequestURL().toString();
prjTmpPath=prjTmpPath.substring(0,path.lastIndexOf("/"));
File tmpFile = File.createTempFile("000000book", ".pdf");
tmpFile.deleteOnExit();
-----------------copy temp file to prjTmpPath-----------------------------------
tmpFile.delete();
File prjTempFile=new File(tmpFile+"/"+tmpFile.getName());
//<------I only want to get the temporary file name for Multi users
prjTempFile.deleteOnExit();
-------------------do--PDF file create here-----------..............and open the created PDF file in the next jsp file.
but when i closed the browser and close the programme ,but the 000000book7109.pdf file is still existed in my project folder.
I think the temporary file will be deleted when the programme terminates or JVM terminates .and i try to close All.for delete it .
I was failed.
what can i do ?
thanks

A couple of things:
1. As a servlet programmer, you have no way of knowing when the JVM running the servlet container is going to close. It could be months before the container is rebooted.
2. DeletOnExit is not guaranteed to work (check the API docs)
3. The appropriate place to delete this file would be after it has been served. Create another servlet for downloading PDF files, then pass in the PDF document name as a parameter. Once the servlet returns the contents of the file to the http stream (there are tons of examples of how to do this type of thing, both in this newsgroup and Google), delete the file.
If deleting the file immediately is not to your liking (who knows, maybe the user needs to be able to click the refresh button), then you can tie the file to the user session and only delete it if the session is no longer valid (natch, you'll have to have a queue of files pending deletion, and run through it every now and then to clean it out).
If you are willing to give up some determinate behavior, I suppose you could delete the file in the finalize() method of a reference object in the session scope, but I'll probably get yelled at for even suggesting it, because there is not guarantee of when (or even if) the finalize() method will be called.
- K

Similar Messages

  • Trouble compiling java files inside the packages.

    Hello I have a question in Java when compiling with packages. Can anyone Help??
    My 2 java files BeerSelect2.java & BeerExpert.java are in packages com.example.web & com.example.model respectively.
    C:\MyProjects\beerV1\src\com\example\web\BeerSelect2.java
    and
    C:\MyProjects\beerV1\src\com\example\model\BeerExpert.java
    I have compiled the BeerExpert.java in the model package.(ie the class file for BeerExpert is in the com.example.model package.)
    My BeerSelect2 file which is inside the web folder is like this
    package com.example.web;
    import com.example.model.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class BeerSelect2 extends HttpServlet
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    out.println("Beer Selection Advice<br>");
    String c=request.getParameter("color");
    out.println("<br> Got Beer color "+c);
    BeerExpert be=new BeerExpert();
    List result=be.getBrands(c);
    response.setContentType("text/html");
    out.println("BEER SELECTION ADVICE <br>");
    Iterator it=result.iterator();
    while(it.hasNext())
    out.print("<br> try: "+it.next());
    This shows 3 comile errors.
    & the BeerExpert.java file which is in the model folder is like this:
    package com.example.model;
    import java.util.*;
    public class BeerExpert
    public List getBrands(String color)
    List brands=new ArrayList();
    if(color.equals("amber"))
    brands.add("Jack Amber");
    brands.add("Red Moose");
    else
    brands.add("Jale pale Ale");
    brands.add("Gout Stout");
    return (brands);
    This compiles fine in the model folder.
    Now when I'm trying to compile my BeerSelect2.java in the 'web' folder in which I'm trying to import the com.example.model.* which is as follows
    C:\MyProjects\beerV1\src\com\example\web>javac BeerSelect2.java
    which gives 3 errors like this
    BeerSelect2.java:3: package com.example.model does not exist
    import com.example.model.*
    ^
    BeerSelect2.java:22:cannot find symbol
    symbol: class BeerExpert
    location: class com.example.web.BeerSelect2.
    BeerExpert be=new BeerExpert();
    ^
    BeerSelect2.java:22:cannot find symbol
    symbol: class BeerExpert
    location: class com.example.web.BeerSelect2.
    BeerExpert be=new BeerExpert();
    ^
    Can anyone help???

    Since the classes are part of the com.example.web and com.example.model packages the most straight forward way to compile is from the folder containing "com". Assuming you want the resulting .class files to be in the same folders are their associated .java source files:
    C:\MyProjects\beerV1\src\> javac -cp . com\example\model\BeerExpert.java
    C:\MyProjects\beerV1\src\> javac -cp . com\example\web\BeerSelect2.javaThe -cp . part is there to set the classpath (the location that the compiler will use to locate java classes) and thereby let the compiler make sense of the import statements.
    The presence of "src" in the directory path strongly suggests, however, that the intention is not to have source and class files end up in the same directory. If this is the case read up on the syntax of the http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html (java.exe) and http://download.oracle.com/javase/6/docs/technotes/tools/windows/javac.html (javac.exe) commands. (paying attention to how searching for types is done). Also read up on any documentation you were given for building the application (if you are modifying something already given).
    If you are using an IDE you should say.

  • File.deleteOnExit Bug?

    Here is my code,
                                cache = new File("C:\\.cache");
                                cache.createNewFile();
                                cache.deleteOnExit();When the VM terminates, the file stays there. I can delete the file using delete(). I'm exiting the VM by closing out my JFrame. Am I just using it incorrectly?
    Edited by: Jadz_Core on Feb 19, 2010 11:54 PM

    This is my code, I'm having trouble reproducing it. I think its because when I exit out of the JFrame, it's causing it to terminate weird or something.
    Relavant lines being:
                            File cache = null;
                                cache = new File(drivesBox.getSelectedItem().toString() + ".cache");
                                cache.createNewFile();
                                cache.deleteOnExit();
                                if (cache != null) {
                                    cache.delete();
    package diskwipe;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.text.DecimalFormat;
    import java.util.LinkedList;
    import java.util.List;
    import javax.swing.JFrame;
    public class DiskWiper extends JFrame {
        public DiskWiper() {
            initComponents();
            setTitle("DiskWipe");
            setResizable(false);
            cancelButton.setEnabled(false);
            prog.setStringPainted(false);
            reloadDrives();
        private void reloadDrives() {
            drivesBox.removeAllItems();
            String[] drives = getDrives();
            for (Object o : drives) {
                drivesBox.addItem(o);
        private static String[] getDrives() {
            File[] roots = File.listRoots();
            List<String> drives = new LinkedList<String>();
            for (File f : roots) {
                if (f.canWrite() && f.getFreeSpace() > 0L) {
                    drives.add(f.getPath());
            return drives.toArray(new String[drives.size()]);
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            //lots of unrelated stuff
        }// </editor-fold>
        private void wipeButtonMouseClicked(java.awt.event.MouseEvent evt) {
            if (wipeButton.isEnabled()) {
                wipeButton.setEnabled(false);
                reloadButton.setEnabled(false);
                drivesBox.setEnabled(false);
                stop = false;
                Thread worker = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        cancelButton.setEnabled(true);
                        prog.setStringPainted(true);
                        try {
                            File cache = null;
                            OutputStream out = null;
                            try {
                                cache = new File(drivesBox.getSelectedItem().toString() + ".cache");
                                cache.createNewFile();
                                cache.deleteOnExit();
                                long totalToWrite = cache.getFreeSpace();
                                long totalWritten = 0L;
                                byte[] buffer = new byte[1024 * 1024 * 32];
                                DecimalFormat format = new DecimalFormat("#0.00");
                                out = new FileOutputStream(cache);
                                while (!stop && totalWritten < totalToWrite) {
                                    out.write(buffer);
                                    totalWritten += buffer.length;
                                    double percent = ((double) totalWritten / totalToWrite) * 100D;
                                    String percentStr = format.format(percent);
                                    prog.setString("Wiping: " + percentStr);
                                    prog.setValue((int) percent);
                            } finally {
                                wipeButton.setEnabled(true);
                                cancelButton.setEnabled(false);
                                prog.setStringPainted(false);
                                reloadButton.setEnabled(true);
                                drivesBox.setEnabled(true);
                                if (out != null) {
                                    out.flush();
                                    out.close();
                                if (cache != null) {
                                    cache.delete();
                        } catch (Exception e) {
                            prog.setString(e.getMessage());
                            e.printStackTrace();
                worker.setPriority(Thread.MIN_PRIORITY);
                worker.setDaemon(true);
                worker.start();
        private void reloadButtonMouseClicked(java.awt.event.MouseEvent evt) {
            if (reloadButton.isEnabled()) {
                reloadDrives();
        private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {
            if (cancelButton.isEnabled()) {
                stop = true;
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new DiskWiper().setVisible(true);
        private boolean stop;
        // Variables declaration - do not modify
        private javax.swing.JButton cancelButton;
        private javax.swing.JComboBox drivesBox;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JProgressBar prog;
        private javax.swing.JButton reloadButton;
        private javax.swing.JButton wipeButton;
        // End of variables declaration
    }Edited by: Jadz_Core on Feb 20, 2010 12:14 AM
    Edited by: Jadz_Core on Feb 20, 2010 12:17 AM

  • Java property file in web.xml?

    I'm having trouble getting a web app to work resonably closely to how I expect:
    I have a property file that is accessed by the package of java classes ( under
    WEB-INF/classes). In the classes ( package com.th.lifeinsruance ) i have a property
    file which is referenced in the java code as com.th.lifeinsurance.xx.properties.
    It seems the only place that wl6.0 is prepared to look for this property file
    is under the /weblogic6.0 dir ( i.e totally outside the web app!!). I would guess
    that I'm supposed to register this property file in web.xml for the app however
    the only examples refer to DataSources and so on ( to set a resource). Is this
    correct? Does someone have an example of a java property file being read correctly
    in its package with the .class files?
    Many Thanks
    Mark

    I've some other solution for the same problem which is working fine for me.
    1) make a jar file only consisting of the properties file
    jar -cvf DescriptionBundle.jar  DescriptionBundle.properties
    2) copy the jar file to the /dist/Portal-inf/lib folder
    3) Use the following code to get the ResourceBundle
    Locale locale = null;
    Locale locale = null;
    locale = Locale.US;
    servletReq.getSession().setAttribute("myLocale", locale);
    ResourceBundle bundle = ResourceBundle.getBundle("DescriptionBundle", locale);
    if (bundle == null) {
         logger.warning("bundle is null");
    for (Enumeration e = bundle.getKeys(); e.hasMoreElements();) {
         String key = (String) e.nextElement();
         String s = bundle.getString(key);
         servletReq.getSession().setAttribute(key, s);
         logger.info("Key is" + key + "value is" + s);
    This solution doesn't suit  the title of the topic but is another way to access the properties files.

  • Java properties file

    Hi ,
    I am using trying to write data to a java properties file , by using the setProperty method and somehow the order of the data is not by the order of inserting it ,Is there a way to use the setProperty method and still keep the order of data in the file after storing it.
    Thanks.

    Eddie404 wrote:
    I am using trying to write data to a java properties file , by using the setProperty method and somehow the order of the data is not by the order of inserting it ,Is there a way to use the setProperty method and still keep the order of data in the file after storing it.It shouldn't matter what order the Properties class uses to write its data. If it does, you aren't doing something right.
    If the order matters, that suggests that somebody is responsible for maintaining the properties via a text editor, or something like that. In which case you shouldn't be using a Properties object which modifies the property file. But as soon as you start having two different processes to maintain the file, you're going to run into trouble. So simplify your life and stop doing that. Either maintain it through the program, or through the text editor, but not both ways.

  • Hi. Having trouble viewing a downloaded file from a site. iPad is telling has not got a app to open file ,but have downloaded so many now and none of them are any help. Tried this on my android phone still nothing. Please can anyone help as slowly ma

    HHi having trouble viewing a downloaded file from a site my iPad is telling me I don have a app to open file . And have downloaded loads of apps and still no joy . Have tried this on my android phone to and still nothing. Please can anyone help as slowly going crazy. Thanks tim

    What type of file?  From what site?  What Apps have you downloaded for it?
    Perhaps if you provide details of what you are doing we can provide more precise help.

  • Java.io.File not found in JDK 1.4

    why the java.io.file is deprecated.
    Frans

    [fthamura],
    why the java.io.file is deprecated.Probably because in J2SE 1.4, the New I/O package java.nio package provides scalable I/O operations for files. Through the File channels, a programmer will be able to provide memory-mapped buffers, improved file locking mechanism and faster I/O transfers with the new API package.
    FransHTH.
    Allen Lai
    Developer Technical Support
    SUN Microsystems
    http://www.sun.com/developers/support/

  • Getting all the members (variables, methods AND method bodies) of a java source file

    For a project I want to programmatically get access to the members of java source file (member variables, methods etc) as well as to the source code of those members. My question is what is the best method for this? So far I have found the following methods:
    Use AST's provided by the Java Source API and Java Tree API, as discussed in the following posts:
    http://today.java.net/pub/a/today/2008/04/10/source-code-analysis-using-java-6-compiler-apis.html
    http://weblogs.java.net/blog/timboudreau/archive/2008/02/see_java_code_t.html
    http://netbeans.dzone.com/announcements/new-class-visualization-module
    This has the disadvantage that the classes actually have to be compilable. When I look at the Netbeans Navigator view however, it provides me with a nicely formatted UI list, regardless of the "compilable" state of the class.
    Thus I started looking at how to do this... The answer appears to be through the use of tools such as JavaCC: https://javacc.dev.java.net/
    ANTLR: http://www.antlr.org/
    which are lexers and parsers of source code. However, since the Navigator panel already does this, couldn't I use part of this code to get me the list of variables and methods in a source file? Does the Navigator API help in this regard?
    Another route seems to be through tools such as
    BeautyJ: http://beautyj.berlios.de/
    which run on top of JavaCC if I am correct, and which has the ability to provide a clean view on your java code (or an XML view). However, BeautyJ does not seem to be too actively developed, and is only j2se1.4 compatible.
    I hope someone can shed a light on the best way to go about what I want to achieve. Somebody already doing this?
    (I crossposted on the Netbeans forums too, hope this is OK...)

    I'm currently developing a LaTeX editor(MDI) and I do the same thing, but I don't know what exactly do you need.

  • How to read the java class file to convert it in java.

    hello all,
    i m developing the java application which generated the java code from the java 'class file' .
    Can anybody please help me, Is any java support for reading the class file? or how to know the class file format?
    I know the application javad, jad, javap which is doing the same thing.
    thanks for reply,
    - Jayd

    do you mean decompiling? there are tons of java decompilers available out there, what exactly are you trying to do here?

  • How to convert a .jsp to a .java/.class file for use in peoplesoft

    Hi java/jsp experts,
    I want to convert a .jsp to a .java/.class file. is there a tool available, please let me know if you have any pointers....
    or can i do it manually:
    these are a few lines that the .jsp contains, and i would like to translate this to be in .java/.class format:
    <%@ page import="sun.misc.BASE64Encoder, javax.crypto., javax.crypto.spec."%>
    <%@ page import="java.util.StringTokenizer" %>
    <%@ page import="java.util.Map" %>
    <%!
    sb.append("<input type=\"hidden\" name=\"orderPage_serialNumber\" value=\"");
    sb.append(serialNumber);
    sb.append("\">\n");
    return sb.toString();
    %>
    how can i translate the above import statements and html elements from jsp to java, please let me know.
    Once i have the .java file created from the .jsp, I will compile .java to create the .class file and invoke the .class in peoplecode by using java apis available in peopletools.
    Thanks in advance.

    Is there a way convert a binary .exe file( compiled by
    another compiler) into Java .class/.jar file ? Anyone
    know of a free program that can do this?It's not possible. There are many decompilers and disassemblers for Java but nothing will take you from ANY binary to Java source. It would be the end of computing as we know it and the beginning of a new era -:)

  • How to convert dll to a java class file?

    Hi folks:
    I have some DLLs in VB and C++ and I wanna to convert them to a java class file. Does anybody know if exist a sw or easy way to do it?
    thanks
    Autair

    Well, I believe you could write JNI to call the functions in the DLLs, although I wouldn't recommend it. (You'd have a non-portable, fragile result.)

  • How to convert java .class file to .dll file

    hi,
    I got a problem, I have to convert my java .class file to .dll file. Microsoft VC++ program will invoke the converted .dll file.
    Is there any other possibility.
    I was confused.
    Cam any body help me. If you are having solution for the can you send to my [email protected] account.
    thanks,

    No, it is not possible to do what you are suggesting. Yes, you could produce a DLL that wraps the JVM and loads your java class exposing a C and/or C++ callable interface, but that is a lot to go through unless your class is VERY complex. Otherwise, you might want to just create and maintain two implementations.

  • How can I share a *.java source file across multiple projects in NetBeans?

    I'm sure this simple and a pretty common operation but how can I share a *.java source file across multiple projects in NetBeans? Right now I keep cut, coping and pasting the same source file between multiple projects to re-use the same code. But I could I make this source file a library file or something like that so that I could access it from any project. I assume this would be a generic operation but I mentioned NetBeans for clarity. Thanks.

    fiebigc wrote:
    I know I mentioned NetBeans but I'm most interested in the generic method for creating a library of source files that I can call into whatever program I am developing. I've done such a thing in C using header files and such but I'm trying to get a direction on how this is accomplished in Java. I'm sorry if I could edit the title I would. If anyone wants to be specific about NetBeans I welcome that too.
    Edited by: fiebigc on Jun 20, 2008 5:57 PM
    >I know I mentioned NetBeans but I'm most interested in the generic method for creating a library of source files that I can call into whatever program I am developing. I've done such a thing in C using header files and such but I'm trying to get a direction on how this is accomplished in Java. I'm sorry if I could edit the title I would. If anyone wants to be specific about NetBeans I welcome that too.
    Edited by: fiebigc on Jun 20, 2008 5:57 PM
    Create a class library.
    Write your code, compile it to .class files, put those class files in a .jar file and include the jar file in the classpath whenever you want to compile a project against it.

  • How can i run a java class file from shell?

    Hi all,
    I've a .class file named "File" that contains Main method, it is in the package "File2".
    How can I run it by shell command?
    PS: "java -cp . file" doesn't work it launch->
    Exception in thread "main" java.lang.NoClassDefFoundError: File2/File (wrong name: File2/File)
    Thanks in advance.

    Just to understand: is File2 ar jar archive or not? If it is a jar archive, have you tried open File2.jar? If File2 is a directory within the current directory, have you tried java -cp . File2/File? I just tested with a set of classes and it works... Let me be precise:
    * Let us imagine you are working in a directory whole path is PathToDir/
    * in this directory you have the classes put in a directory called File2
    * in order to launch File.class then you would have to invoke :
    cd PathToDir/ (just to be sure)
    java -cp . File2/File
    *if you were to do the following then you would have the problem you describe
    cd PathToDir/File2/
    java -cp . File

  • Static lookup lists:read data from a Java *.properties file

    Hi
    i need to make static lookup lists i am using read data from a Java *.properties file
    i am using the Class "PropertyFileBasedLookupViewObjectImpl" that wrote by Steve Muench in ToyStore.
    but i need to use the default language for that i update the loadDataFromPropertiesFile()
    method to find the correct properties file
    String temp=Locale.getDefault().getLanguage();
    String propertyFile =
    getViewDef().getFullName().replace('.', '/')+"_"+temp+ ".properties";
    the problem:
    For English(TEST_en.properties) it is good and working
    For Arabic(TEST_ar.properties) read from correct file _ar.properties
    but the dispaly character is wrong
    When Debug
    In the File 1=&#1583;&#1605;&#1588;&#1602;
    In debug 1=/u32423

    Depending on your use case you can either use a programmatic VO or directly expose the JV class as a data control.
    http://docs.oracle.com/cd/E18941_01/tutorials/jdtut_11r2_36/jdtut_11r2_36.html

Maybe you are looking for

  • Slow Web Export in Aperture 1.5.1

    I feel a little crazy for asking this, but it seems like web exports have gotten significantly slower since I upgraded to Aperture 1.5.1. I cannot find anything on my machine that would cause this. Has anyone else experienced this? -Fletch PowerMac G

  • How do you get IDcs5 to open and display properly??

    Purchased InDesign CS5 and it worked well for the first few months then it decided not to open up properly onscreen? Now when opening all I ever get is a tiny portion of the tool bar appearing in the upper left corner of the screen. If I use the 'exp

  • Keyboard doesn't work on my Satellite L when built-in

    Hi, I have a really strange problem. One day suddenly my keyboard stopped working (doesn't matter if in windows or on boot). I thought maybe some how the cable between keyboard and notebook disconnected and opened the keyboard to check this and reali

  • Renaming filenames and case-sensitivity: a race condition in the OS?

    There appears to be a curious set of circumstances where the OS doesn't allow you to rename a file where the only changes are case-sensitive. For example, "foo.JPG" to "foo.jpg". You can see an example using the command-shell "tcsh". Start this shell

  • Just installed a new 1tb sata drive into an old g5. Now what is the best practice to use it?

    Hey all My old g5s memory was full so installed a new internal drive.  I have so far partitioned and named it so it is on the desktop because I saw that in a youtube vid. I'm wondering if that was the best thing to do to use it and if so how should I