#!/usr/bin/python # Usage: txt2java.py < txtFile > javaFragment # # I often have text blocks that I want to convert into Java. # Typically, this happens in a servlet, where I have formatted # HTML for output. After the initial entering, editing can be a real # pain in the tuckus, so I prefer to have a template HTML file, and # use a script to convert it into something Java can print. # # Implementation note: since these are often static strings, # StringBuffer.append() is more expensive in the runtime than letting # Java do the whole thing as a "String strTmp = line [+ nextLine];" # # This is my first Python program, so it is indubitably infested with # pessimisms and un-Python thinking. Feel free to email me with any # suggestions as to style, structure, procedure, etc. # # , 16 Nov 2000, Seattle, WA USA # # $Id: txt2java.py,v 1.2 2001/10/08 09:15:38 reeses Exp $ import sys, string substitutions = [ ['\\', '\\\\'], ['\r', ''], ['\n', '\\n'], ['\"', '\\\"'] ] def changeLine(sbName,str): "Change text line to be a valid Java statement." result = sbName + ".append(\"" for sub in substitutions: str = string.replace(str, sub[0], sub[1]) result += str result += "\");\n" return result def getInitialisation (sbName): "Set up variables used in Java code segment." result = "java.lang.StringBuffer " + sbName + " = new java.lang.StringBuffer();\n" return result def getClosing (sbName, sName): "Convert StringBuffer to String." result = "java.lang.String " + sName + " = " + sbName + ".toString();\n" return result sbName = "sbTmp"; sName = "strTmp"; sys.stdout.write(getInitialisation(sbName)); for line in sys.stdin.readlines(): sys.stdout.write(changeLine(sbName, line)) sys.stdout.write(getClosing(sbName, sName))