1 package org.enhydra.snapper.utils; 2 3 import java.io.*; 4 5 public class ReadWriteTextFile { 6 7 8 14 static public String getContents(File aFile) { 15 StringBuffer contents = new StringBuffer (); 17 18 BufferedReader input = null; 20 try { 21 input = new BufferedReader( new FileReader(aFile) ); 24 String line = null; while (( line = input.readLine()) != null){ 26 contents.append(line); 27 contents.append(System.getProperty("line.separator")); 28 } 29 } 30 catch (FileNotFoundException ex) { 31 ex.printStackTrace(); 32 } 33 catch (IOException ex){ 34 ex.printStackTrace(); 35 } 36 finally { 37 try { 38 if (input!= null) { 39 input.close(); 41 } 42 } 43 catch (IOException ex) { 44 ex.printStackTrace(); 45 } 46 } 47 return contents.toString(); 48 } 49 50 61 static public void setContents(File aFile, String aContents) 62 throws FileNotFoundException, IOException { 63 if (aFile == null) { 64 throw new IllegalArgumentException ("File should not be null."); 65 } 66 if (!aFile.exists()) { 67 throw new FileNotFoundException ("File does not exist: " + aFile); 68 } 69 if (!aFile.isFile()) { 70 throw new IllegalArgumentException ("Should not be a directory: " + aFile); 71 } 72 if (!aFile.canWrite()) { 73 throw new IllegalArgumentException ("File cannot be written: " + aFile); 74 } 75 76 Writer output = null; 78 try { 79 output = new BufferedWriter( new FileWriter(aFile) ); 81 output.write( aContents ); 82 } 83 finally { 84 if (output != null) output.close(); 86 } 87 } 88 89 public static void main ( String [] aArguments ) throws IOException { 90 File testFile = new File("C:\\Temp\\blah.txt"); 91 setContents(testFile, "blah blah blah"); 92 93 System.out.println( "File contents: " + getContents(testFile) ); 94 } 95 } | Popular Tags |