Georgi Koemdzhiev Georgi Koemdzhiev - 1 year ago 39
Java Question

Write java program as a String using Python

I am trying to write a script that will generate a java file that will be used in Android Studio. the reason I am doing that is because I will be generating different JSON files with different information and I want to generate the appropriate java files using these JSON files if that make sense. Currently, I am testing the whole process of writing a simple java program in a file in the following python script:

dataClass = "public class data {"
mainMethodHeader = "public static void main(String args[]) {"
sys = "System.out.println(\"Hello World!\");"
closingbracket = "}"
wholeProgram = dataClass + mainMethodHeader + sys + closingbracket + closingbracket
json.dump(wholeProgram, open('', 'w+'))

The problem is I cannot compile the since it is string:

enter image description here

Any idea how I can force non-string output in the file so it can be compiled by the java compier?


json.dump will result in a JSON representation of your string. (E.g. foo becomes "foo".)

You should just write the content of the string directly into the file:

with open('', 'w') as out_file: