1 25 package org.ofbiz.base.util; 26 27 import java.io.BufferedWriter ; 28 import java.io.File ; 29 import java.io.FileWriter ; 30 import java.io.IOException ; 31 import java.io.Writer ; 32 import java.io.FileNotFoundException ; 33 import java.io.FileReader ; 34 import java.io.BufferedReader ; 35 36 43 public class FileUtil { 44 45 public static final String module = FileUtil.class.getName(); 46 47 public static void writeString(String fileName, String s) throws IOException { 48 writeString(null, fileName, s); 49 } 50 51 public static void writeString(String path, String name, String s) throws IOException { 52 Writer out = getBufferedWriter(path, name); 53 54 try { 55 out.write(s + System.getProperty("line.separator")); 56 } catch (IOException e) { 57 Debug.logError(e, module); 58 throw e; 59 } finally { 60 if (out != null) { 61 try { 62 out.close(); 63 } catch (IOException e) { 64 Debug.logError(e, module); 65 } 66 } 67 } 68 } 69 70 public static Writer getBufferedWriter(String path, String name) throws IOException { 71 String fileName = getPatchedFileName(path, name); 72 if (UtilValidate.isEmpty(fileName)) { 73 throw new IOException ("Cannot obtain buffered writer for an empty filename!"); 74 } 75 76 return new BufferedWriter (new FileWriter (fileName)); 77 } 78 79 public static String getPatchedFileName(String path, String fileName) throws IOException { 80 if (UtilValidate.isNotEmpty(path)) { 82 path = path.replaceAll("\\\\", "/"); 83 File parentDir = new File (path); 84 if (!parentDir.exists()) { 85 if (!parentDir.mkdir()) { 86 throw new IOException ("Cannot create directory for path: " + path); 87 } 88 } 89 90 if (!path.endsWith("/")) { 92 path = path + "/"; 93 } 94 if (fileName.startsWith("/")) { 95 fileName = fileName.substring(1); 96 } 97 fileName = path + fileName; 98 } 99 100 return fileName; 101 } 102 103 public static StringBuffer readTextFile(String fileName, boolean newline) throws FileNotFoundException , IOException { 104 File file = new File (fileName); 105 if (!file.exists()) { 106 throw new FileNotFoundException (); 107 } 108 109 StringBuffer buf = new StringBuffer (); 110 BufferedReader in = null; 111 try { 112 in = new BufferedReader (new FileReader (file)); 113 114 String str; 115 while ((str = in.readLine()) != null) { 116 buf.append(str); 117 if (newline) { 118 buf.append(System.getProperty("line.separator")); 119 } 120 } 121 } catch (IOException e) { 122 Debug.logError(e, module); 123 throw e; 124 } finally { 125 if (in != null) { 126 try { 127 in.close(); 128 } catch (IOException e) { 129 Debug.logError(e, module); 130 } 131 } 132 } 133 134 return buf; 135 } 136 } 137 | Popular Tags |