1 package xdoclet.junit; 2 3 17 18 import java.io.File ; 19 import java.io.FileWriter ; 20 import java.io.IOException ; 21 22 27 public class FileHandling 28 { 29 private File _tmpDir = null; 30 31 public File getTmpDir() 32 { 33 return _tmpDir; 34 } 35 36 public File write(String name, String content) throws IOException 37 { 38 if (_tmpDir == null) 40 { 41 File dummy = File.createTempFile("dummy", ".java"); 42 String tmpDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar)); 43 44 if ((tmpDir == null) || (tmpDir.length() == 0)) 45 { 46 tmpDir = "."; 47 } 48 dummy.delete(); 49 50 int nr = 0; 51 52 while (_tmpDir == null) 53 { 54 _tmpDir = new File (tmpDir, "test"+nr); 55 if (_tmpDir.exists()) 56 { 57 nr++; 58 _tmpDir = null; 59 } 60 } 61 _tmpDir.mkdir(); 62 } 63 64 String fileName = name.replace('.', File.separatorChar) + ".java"; 66 File srcFile = ensurePath(fileName); 67 FileWriter output = new FileWriter (srcFile.getAbsolutePath()); 68 69 output.write(content); 70 output.close(); 71 return srcFile; 72 } 73 74 public File ensurePath(String fileName) 75 { 76 String shortFileName = fileName; 77 File dir = _tmpDir; 78 int pos = shortFileName.indexOf(File.separatorChar); 79 80 while (pos >= 0) 81 { 82 dir = new File (dir, shortFileName.substring(0, pos)); 83 dir.mkdir(); 84 shortFileName = shortFileName.substring(pos + 1); 85 pos = shortFileName.indexOf(File.separatorChar); 86 } 87 88 return new File (dir, shortFileName); 89 } 90 91 public void removeTmpDir() 92 { 93 if (_tmpDir != null) 94 { 95 removeDir(_tmpDir); 96 } 97 _tmpDir = null; 98 } 99 100 private void removeDir(File dir) 101 { 102 if (dir.exists()) 103 { 104 String [] files = dir.list(); 105 File sub; 106 107 if (files != null) 108 { 109 for (int idx = 0; idx < files.length; idx++) 110 { 111 sub = new File (dir, files[idx]); 112 if (sub.isDirectory()) 113 { 114 removeDir(sub); 115 } 116 else 117 { 118 sub.delete(); 119 } 120 } 121 } 122 dir.delete(); 123 } 124 } 125 } 126 | Popular Tags |