1 18 19 package org.apache.jorphan.io; 20 21 import java.io.BufferedReader ; 22 import java.io.File ; 23 import java.io.FileInputStream ; 24 import java.io.FileOutputStream ; 25 import java.io.FileReader ; 26 import java.io.FileWriter ; 27 import java.io.IOException ; 28 import java.io.InputStreamReader ; 29 import java.io.OutputStreamWriter ; 30 import java.io.Reader ; 31 import java.io.Writer ; 32 33 import org.apache.jorphan.logging.LoggingManager; 34 import org.apache.log.Logger; 35 36 47 public class TextFile extends File 48 { 49 transient private static Logger log = LoggingManager.getLoggerForClass(); 50 51 54 private String encoding= null; 55 56 62 public TextFile(File filename, String encoding) 63 { 64 super(filename.toString()); 65 setEncoding(encoding); 66 } 67 68 74 public TextFile(File filename) 75 { 76 super(filename.toString()); 77 } 78 79 85 public TextFile(String filename) 86 { 87 super(filename); 88 } 89 90 97 public TextFile(String filename, String encoding) 98 { 99 super(filename); 100 } 101 102 108 public void setText(String body) 109 { 110 Writer writer = null; 111 try 112 { 113 if (encoding == null) 114 { 115 writer = new FileWriter (this); 116 } 117 else 118 { 119 writer = new OutputStreamWriter ( 120 new FileOutputStream (this), 121 encoding); 122 } 123 writer.write(body); 124 writer.flush(); 125 writer.close(); 126 } 127 catch (IOException ioe) 128 { 129 try { 130 if (writer != null) { 131 writer.close(); 132 } 133 } catch (IOException e) {} 134 log.error("", ioe); 135 } 136 } 137 138 143 public String getText() 144 { 145 String lineEnd = System.getProperty("line.separator"); 146 StringBuffer sb = new StringBuffer (); 147 Reader reader = null; 148 try 149 { 150 if (encoding == null) 151 { 152 reader= new FileReader (this); 153 } 154 else 155 { 156 reader= new InputStreamReader ( 157 new FileInputStream (this), 158 encoding); 159 } 160 BufferedReader br = new BufferedReader (reader); 161 String line = "NOTNULL"; 162 while (line != null) 163 { 164 line = br.readLine(); 165 if (line != null) 166 { 167 sb.append(line + lineEnd); 168 } 169 } 170 } 171 catch (IOException ioe) 172 { 173 log.error("", ioe); 174 } 175 if (reader != null) 176 try {reader.close();} catch (IOException e) {} 177 return sb.toString(); 178 } 179 180 183 public String getEncoding() 184 { 185 return encoding; 186 } 187 188 191 public void setEncoding(String string) 192 { 193 encoding= string; 194 } 195 } 196 | Popular Tags |