/Users/lyon/j4p/src/futils/Futil.java

1    package futils; 
2     
3    import gui.dialogs.DirectoryChooser; 
4     
5    import javax.swing.*; 
6    import java.awt.*; 
7    import java.io.*; 
8    import java.util.prefs.Preferences; 
9     
10   /** 
11    * The Futil class contains a number of methods for manipulating files. 
12    * 
13    * @author Douglas Lyon 
14    * @version 2.0 
15    */ 
16   public final class Futil { 
17       /** 
18        * Don't let anyone instantiate this class. 
19        */ 
20       private Futil() { 
21       } 
22    
23       private static boolean isSwing = true; 
24       private static File lastSelectedFile = null; 
25    
26       public static void setLookAndFeel() { 
27           try { 
28               UIManager.setLookAndFeel( 
29                       UIManager.getCrossPlatformLookAndFeelClassName()); 
30           } catch (Exception e) { 
31               e.printStackTrace(); 
32           } 
33       } 
34    
35       /** 
36        * Returns the <b><code>file</code></b> instance as a string, reading 
37        * it in, one line at a time. 
38        * 
39        * @param file is used as input 
40        * @return file contents  of the file. 
41        */ 
42       public static String getFile(File file) { 
43           try { 
44               char[] chars = new char[(int) file.length()]; 
45               BufferedReader in = new BufferedReader(new FileReader(file)); 
46               in.read(chars); 
47               in.close(); 
48               return new String(chars); 
49           } catch (IOException e) { 
50               System.out.println("failed reading " + 
51                       file.getName() + 
52                       ": " + 
53                       e); 
54               return null; 
55           } 
56       } 
57    
58       public static void testGetFile() { 
59           String s = Futil.getFile(Futil.getReadFile("select a file")); 
60           System.out.println(s); 
61       } 
62    
63       public static void saveFile(File file, 
64                                   String newText) { 
65           try { 
66               char[] chars = newText.toCharArray(); 
67               BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
68               out.write(chars); 
69               out.close(); 
70           } catch (IOException e) { 
71               System.out.println("failed reading " 
72                       + 
73                       file.getName() 
74                       + ": " + e); 
75           } 
76       } 
77    
78       public static void binaryCopyFile() { 
79           byte b[] = readBytes(getReadFile("select a file")); 
80           writeBytes(getWriteFile("select a file to copy to"), 
81                   b); 
82           System.out.println("copy done!"); 
83       } 
84    
85       /** 
86        * copy the file input stream into the file output stream. 
87        */ 
88       public static void binaryCopyFile(FileInputStream fis, 
89                                         FileOutputStream fos) 
90               throws IOException { 
91           byte buffer[] = new byte[512]; 
92           int count; 
93           while ((count = fis.read(buffer)) > 0) 
94               fos.write(buffer, 0, count); 
95    
96    
97       } 
98    
99       public static void print(byte b[]) { 
100          for (int i = 0; i < b.length; i++) { 
101              if ((i % 10) == 0) 
102                  System.out.println(); 
103              System.out.print(b[i] + " "); 
104          } 
105      } 
106   
107      /** 
108       * Futil.writeBytes inputs a File, f and byte array. 
109       * <p/> 
110       * Any failures cause readBytes to return false and a message is 
111       * printed to the console. Otherwise, writeBytes returns true. 
112       */ 
113      public static boolean writeBytes(File f, 
114                                       byte b[]) { 
115          FileOutputStream fos = null; 
116          try { 
117              fos = new FileOutputStream(f); 
118              fos.write(b); 
119              fos.close(); 
120              return true; 
121          } catch (IOException e) { 
122              System.out.println("Futil.writeBytes,Could not open" + 
123                      f); 
124              return false; 
125          } 
126      } 
127   
128      /** 
129       * Futil.readBytes inputs a File, f and returns an array of bytes read 
130       * from the file. Any failures cause readBytes to return null. A 
131       * message is printed to the console. 
132       */ 
133      public static byte[] readBytes(File f) { 
134          FileInputStream fis = null; 
135          int sizeInBytes = -1; 
136          byte buffer[] = null; 
137          try { 
138              fis = new FileInputStream(f); 
139              sizeInBytes = fis.available(); 
140              buffer = new byte[sizeInBytes]; 
141              fis.read(buffer); 
142              fis.close(); 
143          } catch (IOException e) { 
144              System.out.println("Futil:readBytes, Could not open file"); 
145          } 
146          return buffer; 
147      } 
148   
149   
150      /** 
151       * copy and input file to an output file. 
152       */ 
153      public static void copyFile(BufferedReader br, 
154                                  BufferedWriter bw) 
155              throws IOException { 
156          String line = null; 
157          while ((line = 
158                  br.readLine()) != null) 
159              bw.write(line + "\n"); 
160          br.close(); 
161          bw.close(); 
162      } 
163   
164   
165      public static FileOutputStream getFileOutputStream(String prompt) { 
166          return getFileOutputStream(getWriteFile(prompt)); 
167      } 
168   
169      public static FileOutputStream getFileOutputStream(File f) { 
170          try { 
171              return new FileOutputStream(f); 
172          } catch (Exception e) { 
173              System.out.println("Er: FileOutputStream in Futil.java"); 
174          } 
175          return null; 
176      } 
177   
178      public static FileInputStream getFileInputStream(String prompt) { 
179          try { 
180              return new FileInputStream(Futil.getReadFile(prompt)); 
181          } catch (Exception e) { 
182              System.out.println("Er: FileOutputStream in Futil.java"); 
183          } 
184          return null; 
185      } 
186   
187      /** 
188       * check the state of the <code>isSwing</code> property. If false, AWT 
189       * will be used, instead (mostly). 
190       * 
191       * @return 
192       */ 
193      public static boolean isSwing() { 
194          return isSwing; 
195      } 
196   
197      /** 
198       * Use to set if swing is used for open dialog boxes. 
199       * 
200       * @param b 
201       */ 
202      public static void setSwing(boolean b) { 
203          isSwing = b; 
204      } 
205   
206   
207      /** 
208       * Some versions of windows will create a .* suffix on a file name The 
209       * following code will strip it: 
210       */ 
211   
212      public static String FilterFileNameBug(String fname) { 
213          if (fname.endsWith(".*.*")) { 
214              fname = 
215                      fname.substring(0, 
216                              fname.length() - 4); 
217          } 
218          return fname; 
219      } 
220   
221   
222      /** 
223       * @param file Open the <code>file</code> 
224       * @return <code>-1</code> if file cannot be opened. Otherwise return 
225       *         the size, in bytes. 
226       */ 
227      public static int available(File file) { 
228          FileInputStream fis = null; 
229          int sizeInBytes = -1; 
230          if (file.isDirectory()) return -1; 
231          try { 
232              fis = new FileInputStream(file); 
233              sizeInBytes = fis.available(); 
234              fis.close(); 
235          } catch (IOException e) { 
236              System.out.println("Futil:Could not open file"); 
237          } 
238          return sizeInBytes; 
239      } 
240   
241      public static void close(OutputStream os) { 
242          try { 
243              os.close(); 
244          } catch (IOException exe) { 
245              System.out.println("futil: could not close output stream"); 
246          } 
247      } 
248   
249   
250      /** 
251       * Inputs a path to a file, lists all the files in the directory and 
252       * renames them so that they are lower case. 
253       * 
254       * @param thePath the path to file used for processing. 
255       */ 
256      public static void lowerFileNames(File thePath) { 
257          String[] fileNames = thePath.list(); 
258          String pathstr = thePath.getPath(); 
259          for (int i = 0; 
260               fileNames != null && 
261                  i < fileNames.length; i++) { 
262              String aFileName = fileNames[i]; 
263              String newFileName = aFileName.toLowerCase(); 
264              File theFile = new File(pathstr, 
265                      aFileName); 
266              if (theFile.isFile()) { 
267                  //rename theFile to lower case 
268                  System.out.print(i + ":" + aFileName); 
269                  theFile.renameTo(new File(pathstr, 
270                          newFileName)); 
271                  System.out.println("\t==>\t" + newFileName); 
272              } else { 
273                  //case theFile is Dir, in the Dir, repeat same procedure 
274                  System.out.println("Dir:" + aFileName); 
275                  lowerFileNames(new File(pathstr + 
276                          aFileName)); 
277              } 
278          } 
279          return; 
280      }//lowerFileNames 
281   
282      /** 
283       * inputs all the files in a directory and outputs a series of HREFS in 
284       * gui.html as a table of contents. 
285       */ 
286      public static void makeTocHtml() { 
287          File[] files = WriterUtil.getFiles("select an .html file"); 
288          System.out.println(files.length + 
289                  " file(s):"); 
290          FileWriter fw = WriterUtil.getFileWriter( 
291                  "Where do you want me to save your TOC.html?"); 
292          PrintWriter pw = new PrintWriter(fw); 
293          writeTocInHtml(pw, files); 
294          WriterUtil.close(fw); 
295      } 
296   
297      public static void testGetReadFile() { 
298          System.out.println("you selected:" 
299                  + 
300                  getReadFile("select a file...")); 
301      } 
302   
303      /** 
304       * Return a directory that represents the parent of the selected file. 
305       * Remember the last place you were by storing in in the 
306       * <code>Preferences.userRoot</code> 
307       * 
308       * @param prompt appears in the dialog box 
309       * @return User selected <code>File</code> or <code>null</code>. 
310       */ 
311      public static File getReadFileDir(String prompt) { 
312          return getReadFile(prompt).getParentFile(); 
313      } 
314   
315      /** 
316       * Return a file instance. Remember the last place you were by storing 
317       * in in the <code>Preferences.userRoot</code> 
318       * 
319       * @param prompt 
320       * @return 
321       */ 
322      public static File getReadFile(String prompt) { 
323          if (isSwing()) return getReadSwingFile(prompt); 
324          return getReadFileAWT(prompt); 
325      } 
326   
327      private static final String key = "lastDirectoryVisitedForRead"; 
328   
329      private static File getReadSwingFile(String prompt) { 
330          Preferences p = Preferences.userRoot(); 
331   
332          String directory = p.get(key, null); 
333          if (directory != null) { 
334              final File currentDirectory = new File(directory); 
335              JFileChooser jfc = new JFileChooser(currentDirectory); 
336              return jGetFileHelper(jfc, prompt, p, key); 
337          } 
338          JFileChooser jfc1 = new JFileChooser(lastSelectedFile); 
339          return jGetFileHelper(jfc1, prompt, p, key); 
340      } 
341   
342      private static File jGetFileHelper(JFileChooser jfc1, 
343                                         String prompt, 
344                                         Preferences p, 
345                                         final String key) { 
346          jfc1.setToolTipText(prompt); 
347          jfc1.setDialogTitle(prompt); 
348          jfc1.showOpenDialog(new JFrame(prompt)); 
349          final File f = jfc1.getSelectedFile(); 
350          p.put(key, f.getParent()); 
351          return f; 
352      } 
353   
354      // File f = getReadFile("select a file"); 
355      public static File getReadFileAWT(String prompt) { 
356          FileDialog fd = new FileDialog(new Frame(prompt), 
357                  prompt); 
358          fd.setVisible(true); 
359          return new File(fd.getDirectory() + fd.getFile()); 
360      } 
361   
362      public static File JGetReadFile(String prompt) { 
363          JFileChooser jfc = new JFileChooser(lastSelectedFile); 
364          jfc.setToolTipText(prompt); 
365          jfc.setDialogTitle(prompt); 
366          jfc.showOpenDialog(new JFrame(prompt)); 
367          return jfc.getSelectedFile(); 
368      } 
369   
370      private static void testGetReadDirs() { 
371          File f[] = getReadDirs(); 
372          if (f == null) System.exit(0); 
373          for (int i = 0; i < f.length; i++) 
374              System.out.println(f[i]); 
375      } 
376   
377      private static void testGetReadFiles() { 
378          File f[] = getReadFiles(); 
379          if (f == null) System.exit(0); 
380          for (int i = 0; i < f.length; i++) 
381              System.out.println(f[i]); 
382          testGetReadFiles(); 
383      } 
384   
385      public static javax.swing.filechooser.FileFilter getFileFilter( 
386              String suffix) { 
387          class MyFilter extends javax.swing.filechooser.FileFilter { 
388              String suffix = ""; 
389   
390              MyFilter(String s) { 
391                  suffix = s; 
392              } 
393   
394              public boolean accept(File file) { 
395                  String filename = file.getName(); 
396                  return filename.endsWith(suffix); 
397              } 
398   
399              public String getDescription() { 
400                  return "*" + suffix; 
401              } 
402          } 
403          return new MyFilter(suffix); 
404      } 
405   
406      /** 
407       * Only allow the user to select directories 
408       * 
409       * @return the list of directories selected by the user. 
410       */ 
411      public static File[] getReadDirs() { 
412          JFileChooser jfc = null; 
413          if (lastSelectedFile != null) 
414              jfc = new JFileChooser(lastSelectedFile); 
415          else 
416              jfc = new JFileChooser(); 
417          jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); 
418          jfc.setMultiSelectionEnabled(true); 
419          // Show the dialog; wait until dialog is closed 
420          int result = jfc.showOpenDialog(null); 
421          if (result == JFileChooser.APPROVE_OPTION) { 
422              lastSelectedFile = 
423                      jfc.getSelectedFiles()[0].getAbsoluteFile(); 
424              return jfc.getSelectedFiles(); 
425          } 
426          return null; 
427      } 
428   
429      /** 
430       * Only allow the user to select read files. 
431       * 
432       * @param ff 
433       * @return 
434       */ 
435      public static File[] getReadFiles( 
436              javax.swing.filechooser.FileFilter ff) { 
437          JFileChooser jfc = null; 
438          if (lastSelectedFile != null) 
439              jfc = new JFileChooser(lastSelectedFile); 
440          else 
441              jfc = new JFileChooser(); 
442          jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); 
443          jfc.setMultiSelectionEnabled(true); 
444          jfc.addChoosableFileFilter(ff); 
445          // Show the dialog; wait until dialog is closed 
446          int result = jfc.showOpenDialog(null); 
447          if (result == JFileChooser.APPROVE_OPTION) { 
448              lastSelectedFile = 
449                      jfc.getSelectedFiles()[0].getAbsoluteFile(); 
450              return jfc.getSelectedFiles(); 
451          } 
452          return null; 
453      } 
454   
455   
456      public static File[] getReadFiles() { 
457          JFileChooser jfc = null; 
458          if (lastSelectedFile != null) 
459              jfc = new JFileChooser(lastSelectedFile); 
460          else 
461              jfc = new JFileChooser(); 
462          jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); 
463          jfc.setMultiSelectionEnabled(true); 
464          // Show the dialog; wait until dialog is closed 
465          int result = jfc.showOpenDialog(null); 
466          if (result == JFileChooser.APPROVE_OPTION) { 
467              lastSelectedFile = 
468                      jfc.getSelectedFiles()[0].getAbsoluteFile(); 
469              return jfc.getSelectedFiles(); 
470          } 
471          return null; 
472      } 
473   
474      public static File getReadDirFile(String prompt) { 
475          String dir = DirectoryChooser.getDirectory(prompt); 
476          if (dir == null) return null; 
477          File f = new File(dir); 
478          return f; 
479      } 
480   
481   
482      private static void writeTocInHtml(PrintWriter pw, 
483                                         File files[]) { 
484          pw.println("<HTML>"); 
485          pw.println("<BODY>"); 
486          pw.println("<ul>"); 
487          for (int i = 0; i < files.length; i++) { 
488              pw.println("<LI><a href = \"" + 
489                      files[i] + 
490                      "\">" + 
491                      files[i] + 
492                      "</a><P>"); 
493              System.out.println(files[i]); 
494          } 
495          pw.println("</ul>"); 
496          pw.println("</BODY>"); 
497          pw.println("</HTML>"); 
498      } 
499   
500   
501      void writeObject(ObjectOutputStream oos) 
502              throws IOException { 
503          oos.defaultWriteObject(); 
504      } 
505   
506      void readObject(ObjectInputStream ois) 
507              throws ClassNotFoundException, 
508                     IOException { 
509          ois.defaultReadObject(); 
510      } 
511   
512      public static void testCopyFile() { 
513          Examples.testCopyFile(); 
514   
515      } 
516   
517      public static File getWriteFile(String prompt) { 
518          if (isSwing()) 
519              return getWriteFileSwing(prompt); 
520          return getWriteFileAWT(prompt); 
521      } 
522   
523      private static File getWriteFileAWT(String prompt) { 
524          FileDialog fd = 
525                  new FileDialog(new Frame(), 
526                          prompt, 
527                          FileDialog.SAVE); 
528          fd.setVisible(true); 
529   
530          return new File(fd.getDirectory() 
531                  + fd.getFile()); 
532      } 
533   
534      public static File getWriteFileSwing(String prompt) { 
535          Preferences p = Preferences.userRoot(); 
536          String directory = p.get(key, null); 
537          JFileChooser fd = 
538                  new JFileChooser(prompt); 
539          if (directory != null) 
540              fd.setCurrentDirectory(new File(directory)); 
541          fd.showSaveDialog(new JFrame()); 
542   
543          return 
544                  fd.getSelectedFile(); 
545      } 
546   
547   
548      public static void readDataFile(String fn, 
549                                      double data[]) { 
550          System.out.println("processing:\t" + fn); 
551          FileInputStream is = 
552                  getFileInputStream(fn); 
553          InputStreamReader isr = new InputStreamReader(is); 
554          BufferedReader br = new BufferedReader(isr); 
555          StreamTokenizer tokens = new StreamTokenizer(br); 
556          int next = 0; 
557          int num = 0; 
558          try { 
559              while ((next = tokens.nextToken()) != 
560                      StreamTokenizer.TT_EOF) { 
561                  switch (next) { 
562                      case StreamTokenizer.TT_WORD: 
563                          break; 
564                      case StreamTokenizer.TT_NUMBER: 
565                          data[num] = tokens.nval; 
566                          System.out.println(num + 
567                                  ": " + 
568                                  data[num]); 
569                          num = num + 1; 
570                          break; 
571                      case StreamTokenizer.TT_EOL: 
572                          break; 
573                  } 
574              } 
575   
576          } catch (Exception exe) { 
577              System.out.println("listFilteredHrefFile:er!"); 
578          } 
579          close(is); 
580      } 
581   
582      public static FileInputStream getFileInputStream(File file) { 
583          FileInputStream fis = null; 
584          try { 
585              fis = new FileInputStream(file); 
586          } catch (IOException e) { 
587              System.out.println("futil:Could not open file"); 
588          } 
589          return fis; 
590      } 
591   
592      public static FileReader getFileReader(String prompt) { 
593          FileReader fr = null; 
594          try { 
595              fr = 
596                      new FileReader(getReadFile(prompt)); 
597          } catch (IOException e) { 
598              System.out.println("futil:Could not get file"); 
599          } 
600          return fr; 
601      } 
602   
603      public static FileWriter getFileWriter() { 
604          FileWriter fw = null; 
605          try { 
606              fw = 
607                      new FileWriter(getWriteFile("select out file")); 
608          } catch (IOException e) { 
609              System.out.println("futil:Could not create file"); 
610          } 
611          return fw; 
612      } 
613   
614      public static void close(InputStream is) { 
615          try { 
616              is.close(); 
617          } // end try 
618          catch (IOException exe) { 
619              System.out.println("futil: could not close input stream"); 
620          } 
621      } 
622   
623      public static void writeFilteredHrefFile(File inputFile, 
624                                               String outputName) { 
625          System.out.println("Filtering:\t" + 
626                  inputFile + 
627                  "\t>\t" + 
628                  outputName); 
629          try { 
630              FileInputStream is = new FileInputStream(inputFile); 
631              InputStreamReader isr = new InputStreamReader(is); 
632              BufferedReader br = new BufferedReader(isr); 
633              StreamTokenizer tokens = new StreamTokenizer(br); 
634              FileWriter os = new FileWriter(outputName); 
635              PrintWriter output = new PrintWriter(os); 
636              int i; 
637              int next = 0; 
638              tokens.resetSyntax(); 
639              tokens.wordChars(0, 255); 
640              tokens.quoteChar('"'); 
641              while ((next = tokens.nextToken()) != 
642                      StreamTokenizer.TT_EOF) { 
643                  switch (next) { 
644                      case '"': 
645                          output.print('"'); 
646                          for (i = 0; i < 
647                                  tokens.sval.length(); i++) 
648                              if (tokens.sval.charAt(i) == 
649                                      ' ') 
650                                  output.print("%20"); 
651                              else 
652                                  output.print(tokens.sval.charAt(i)); 
653                          output.print('"'); 
654                          break; 
655                      case StreamTokenizer.TT_WORD: 
656                          output.print(tokens.sval + 
657                                  " "); 
658                          break; 
659                      case StreamTokenizer.TT_NUMBER: 
660                          output.print(tokens.nval + 
661                                  " "); 
662                          break; 
663                      case StreamTokenizer.TT_EOL: 
664                          output.println(); 
665                          break; 
666                  } // end switch 
667              } // end while 
668              is.close(); 
669              os.close(); 
670          } // end try 
671          catch (Exception exe) { 
672              System.out.println("writeFilteredHrefFile:er!"); 
673          } 
674      } 
675   
676      public static String getReadFileName(String prompt) { 
677          FileDialog fd = new 
678                  FileDialog(new Frame(), prompt); 
679          fd.show(); 
680          String file_name = fd.getFile(); 
681          if (fd.getFile() == null) return null; 
682          String path_name = fd.getDirectory(); 
683          String file_string = path_name + 
684                  file_name; 
685          //println("Opening file: "+file_string); 
686          fd.dispose(); 
687          return file_string; 
688      } 
689   
690      public static String getReadFileName() { 
691          return 
692                  getReadFileName("select a file"); 
693      } 
694   
695      public static boolean fileExists(String s) { 
696          File f = new File(s); 
697          return f.exists(); 
698      } 
699   
700      public static byte[] getBytes(File f) { 
701          byte b[] = null; 
702          try { 
703              FileInputStream fis = new FileInputStream(f); 
704              b = new byte[fis.available()]; 
705              fis.read(b); 
706              fis.close(); 
707          } catch (IOException e) { 
708              System.out.println("futil:Could not open file"); 
709          } 
710          return b; 
711      } 
712   
713      public static void main(String[] args) { 
714          final File readFile = Futil.getReadFile("select a file"); 
715          System.out.println(readFile.toString()); 
716      } 
717   
718      private static void testGetDirFile() { 
719          System.out.println( 
720                  getReadDirFile("please select a directory").toString()); 
721      } 
722  } 
723