1 25 26 package task; 27 28 import java.io.BufferedReader ; 29 import java.io.File ; 30 import java.io.FileReader ; 31 import java.io.FileWriter ; 32 import java.io.IOException ; 33 import java.io.PrintWriter ; 34 import java.util.Iterator ; 35 import java.util.LinkedList ; 36 import java.util.List ; 37 import org.apache.tools.ant.BuildException; 38 import org.apache.tools.ant.DirectoryScanner; 39 import org.apache.tools.ant.Project; 40 import org.apache.tools.ant.Task; 41 import org.apache.tools.ant.types.FileSet; 42 43 52 public class Txt2Html 53 extends Task 54 { 55 56 57 private File todir; 58 59 60 private List filesets = new LinkedList (); 61 62 67 public void setTodir( File todir ) { 68 this.todir = todir; 69 } 70 71 76 public void addFileset( FileSet fs ) { 77 filesets.add( fs ); 78 } 79 80 86 public void execute() 87 throws BuildException 88 { 89 int count = 0; 90 91 Iterator iter = filesets.iterator(); 93 while( iter.hasNext() ) { 94 FileSet fs = (FileSet)iter.next(); 95 DirectoryScanner ds = fs.getDirectoryScanner( project ); 96 File basedir = ds.getBasedir(); 97 String [] files = ds.getIncludedFiles(); 98 for( int i = 0; i < files.length; i++ ) { 99 File from = new File ( basedir, files[i] ); 100 File to = new File ( todir, files[i] + ".html" ); 101 if( !to.exists() || 102 (from.lastModified() > to.lastModified()) ) 103 { 104 log( "Converting file '" + from.getAbsolutePath() + 105 "' to '" + to.getAbsolutePath(), Project.MSG_VERBOSE ); 106 try { 107 convert( from, to ); 108 } 109 catch( IOException e ) { 110 throw new BuildException( "Could not convert '" + 111 from.getAbsolutePath() + "' to '" + 112 to.getAbsolutePath() + "'", e ); 113 } 114 count++; 115 } 116 } 117 if( count > 0 ) { 118 log( "Converted " + count + " file" + (count > 1 ? "s" : "") + 119 " to " + todir.getAbsolutePath() ); 120 } 121 } 122 } 123 124 131 private void convert( File from, File to ) 132 throws IOException 133 { 134 BufferedReader in = new BufferedReader ( new FileReader ( from ) ); 136 PrintWriter out = new PrintWriter ( new FileWriter ( to ) ); 137 138 out.println( "<html><body><pre>" ); 140 141 String line; 143 while( (line = in.readLine()) != null ) { 144 StringBuffer result = new StringBuffer (); 145 int len = line.length(); 146 for( int i = 0; i < len; i++ ) { 147 char c = line.charAt( i ); 148 switch( c ) { 149 case '&': 150 result.append( "&" ); 151 break; 152 case '<': 153 result.append( "<" ); 154 break; 155 default: 156 result.append( c ); 157 } 158 } 159 out.println( result.toString() ); 160 } 161 162 out.println( "</pre></body></html>" ); 164 165 out.close(); 167 in.close(); 168 } 169 170 } 171 172 173 | Popular Tags |