001 /*
002 * LAPIS lightweight structured text processing system
003 *
004 * Copyright (C) 1998-2002 Carnegie Mellon University,
005 * Copyright (C) 2003 Massachusetts Institute of Technology.
006 * All rights reserved.
007 *
008 * This library is free software; you can redistribute it
009 * and/or modify it under the terms of the GNU General
010 * Public License as published by the Free Software
011 * Foundation, version 2.
012 *
013 * LAPIS homepage: http://graphics.lcs.mit.edu/lapis/
014 */
015
016 package lapisx.io;
017
018 //import java.net.*;
019 import java.io.*;
020 import java.util.Vector;
021
022 public abstract class TempFile {
023 private static String tempDir;
024 private static Vector temps = new Vector ();
025
026 static {
027 if (!(tryTempDir (getTempDirProperty ())
028 || tryTempDir ("c:\\temp") // Windows
029 || tryTempDir ("c:\\windows\\temp") // also Windows
030 || tryTempDir ("/tmp") // Unix
031 ))
032 useTempDir (""); // default to current directory
033 }
034
035 private static String getTempDirProperty () {
036 try {
037 return System.getProperty ("temp.directory");
038 } catch (SecurityException e) {
039 return null;
040 }
041 }
042
043 private static boolean tryTempDir (String dir) {
044 if (dir == null)
045 return false;
046
047 File f = new File (dir);
048 if (!f.exists ()) {
049 //System.err.println (dir + " does not exist");
050 return false;
051 }
052
053 if (!f.isDirectory ()) {
054 //System.err.println (dir + " not a directory");
055 return false;
056 }
057
058
059 if (dir.length () > 0
060 && !(dir.endsWith ("/") ||
061 dir.endsWith (File.separator)))
062 dir += File.separator;
063 useTempDir (dir);
064 return true;
065 }
066
067 private static void useTempDir (String dir) {
068 tempDir = dir;
069 }
070
071 public static String getTempDirectory () {
072 return tempDir;
073 }
074
075 public static File makeTempFile (String basename, String extension) {
076 String dir = getTempDirectory ();
077 File f;
078 synchronized (temps) {
079 do
080 f = new File (dir
081 + basename
082 + String.valueOf ((int)(Math.random() * 999999))
083 + extension);
084 while (temps.contains (f) || f.exists());
085 registerTempFile (f);
086 }
087 return f;
088 }
089
090 public static void registerTempFile (File f) {
091 temps.addElement (f);
092 }
093
094 public static void deleteAllTempFiles () {
095 synchronized (temps) {
096 for (int i=0; i<temps.size(); ++i) {
097 File f = (File)temps.elementAt(i);
098 f.delete ();
099 }
100 temps.setSize (0);
101 }
102 }
103 }