1 11 package org.eclipse.jdt.internal.core.util; 12 13 import java.io.File ; 14 import java.io.IOException ; 15 import java.io.RandomAccessFile ; 16 import java.net.URL ; 17 18 21 public class AnonymousFileSource { 22 File fDirectory; 23 26 public AnonymousFileSource(File directory) { 27 if (!directory.exists()) { 28 directory.mkdirs(); 29 } else if (!directory.isDirectory()) { 30 throw new IllegalArgumentException ("Directory arguments should be a directory."); } 32 fDirectory = directory; 33 } 34 38 synchronized public RandomAccessFile allocateAnonymousFile() throws IOException { 39 40 File file = getAnonymousFile(); 41 return new RandomAccessFile (file, "rw"); } 43 47 synchronized public URL allocateAnonymousURL(byte[] bytes) throws IOException { 48 try { 49 byte hasharray[] = java.security.MessageDigest.getInstance("SHA").digest(bytes); StringBuffer sb = new StringBuffer (); 51 for (int i = 0; i < hasharray.length; i++) { 52 sb.append(Character.forDigit((hasharray[i] >> 4) & 0x0F, 16)); 53 sb.append(Character.forDigit(hasharray[i] & 0x0F, 16)); 54 } 55 sb.append(".jnk"); String fileName = sb.toString(); 57 File file = fileForName(fileName); 58 if (!file.exists()) { 59 RandomAccessFile raf = new RandomAccessFile (file, "rw"); raf.write(bytes); 61 raf.close(); 62 } 63 return convertFileToURL(file); 64 } 65 catch (java.security.NoSuchAlgorithmException e) { 66 throw new IOException (e.getMessage()); 67 } 68 } 69 72 static public URL convertFileToURL(File file) { 73 try { 74 String path = file.getCanonicalPath().replace(java.io.File.separatorChar, '/'); 75 return new URL ("file", "", "/" + path); } 77 catch (IOException ioe) { 78 throw new Error (); 79 } 80 } 81 84 File fileForName(String fileName) { 85 File dir; 86 if (fileName.length() >= 1) { 87 String dirName = Integer.toHexString((fileName.hashCode() % 255) & 255); 88 dir = new File (fDirectory, dirName); 89 dir.mkdirs(); 90 } else { 91 dir = fDirectory; 92 } 93 return new File (dir, fileName); 94 } 95 99 synchronized public File getAnonymousFile() { 100 File file; 101 file = fileForName(getAnonymousFileName()); 102 while (file.exists()) { 103 try { 104 Thread.sleep(1); 105 } 106 catch (InterruptedException e) { 107 } 109 file = fileForName(getAnonymousFileName()); 110 } 111 return file; 112 } 113 117 synchronized public String getAnonymousFileName() { 118 return getAnonymousFileName(System.currentTimeMillis()); 119 } 120 124 synchronized public String getAnonymousFileName(long l) { 125 if (l < 0) l = -l; 126 StringBuffer sb = new StringBuffer (); 127 sb.append(Character.forDigit((int)(l % 26 + 10), 36)); 128 l /= 26; 129 while (l != 0) { 130 sb.append(Character.forDigit((int)(l % 36), 36)); 131 l /= 36; 132 } 133 sb.append(".jnk"); return sb.toString(); 135 } 136 } 137 | Popular Tags |