1 package com.flexiblewebsolutions.io.util;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.File;
6 import java.io.FileNotFoundException;
7 import java.io.FileReader;
8 import java.io.FileWriter;
9 import java.io.IOException;
10 import java.io.PrintWriter;
11
12 import org.apache.log4j.Logger;
13
14 /***
15 * Utility methods for reading and writing files
16 *
17 * @author Donavon Buss
18 */
19 public class FileUtils
20 {
21 static Logger logger = Logger.getLogger( FileUtils.class.getName() );
22
23 /***
24 * Reads in xml from file, removes commented out text, and then loads result
25 * into a StringBuffer.
26 *
27 * @param pFile
28 * XML file
29 * @return The XML Contents of the file
30 */
31 public StringBuffer loadXMLFileToString( File pFile )
32 {
33 StringBuffer pageContents = new StringBuffer();
34 BufferedReader reader = null;
35 try
36 {
37 reader = new BufferedReader( new FileReader( pFile ) );
38 String line = null;
39
40 while( ( line = reader.readLine() ) != null )
41 {
42 pageContents.append( line );
43 pageContents.append( "\n" );
44 }
45 }
46 catch( FileNotFoundException fnfe )
47 {
48 System.err.println( "Error, could not find requested input file: "
49 + pFile.getAbsolutePath() + " because of error: "
50 + fnfe.getMessage() );
51 }
52 catch( IOException ioe )
53 {
54 System.err.println( "Error occurred while writing file: "
55 + pFile.getAbsolutePath() + " becasue of error: "
56 + ioe.getMessage() );
57 }
58 finally
59 {
60 try
61 {
62 reader.close();
63 reader = null;
64 }
65 catch( Exception e )
66 {
67 System.err.println( "Non critical error: Reader could not close" );
68 }
69 }
70
71
72 String startComment = "<!--";
73 String endComment = "-->";
74
75 while( pageContents.indexOf( startComment ) != -1 )
76 {
77 int startIndex = pageContents.indexOf( startComment );
78 int endIndex = pageContents.indexOf( endComment )
79 + endComment.length();
80 pageContents.delete( startIndex, endIndex );
81 }
82 return ( pageContents );
83 }
84
85 /***
86 * Write contents of a StringBuffer to file.
87 *
88 * @param pFile -
89 * Name of file to be written
90 * @param pData -
91 * File data
92 */
93 public void writeFile( File pFile, StringBuffer pData )
94 {
95 PrintWriter writer = null;
96 try
97 {
98 writer = new PrintWriter( new BufferedWriter(
99 new FileWriter( pFile ) ) );
100 writer.println( pData.toString() );
101 logger.debug( pFile.getAbsolutePath() + " written." );
102 }
103 catch( IOException e )
104 {
105 logger.error( "Error writing file " + pFile.getAbsolutePath(), e );
106 e.printStackTrace();
107 }
108 finally
109 {
110 try
111 {
112 writer.close();
113 }
114 catch( Exception e )
115 {
116
117 }
118 }
119 }
120 }