u.jegan
u.jegan

Reputation: 833

is this the right way to create a java file (Programmatically)?

Below is the code to create a java file programmatically

is this the right way? or is there any other way

public static void main(String[] args) throws IOException {
        File atlas = new File("D:/WIP/pac/n/sample.txt");
        if (!atlas.exists()) {
            System.out.println("File not exist");
        }
        FileHandle mAtlasHandle = new FileHandle(atlas);
        BufferedReader reader = mAtlasHandle.reader(1024);
        String line = null;
        ArrayList<String> mArrayList = new ArrayList<String>();
        while ((line = reader.readLine()) != null) {
            mArrayList.add(line);
        }
        File file = new File("D:/WIP/pac/n/Sample.java");
        if (!file.exists()) {
            file.createNewFile();
        }
        String packageName = "package com.atom.lib;";
        PrintWriter writer = new PrintWriter(file);
        String mString = new String(file.getName());
        String name = mString.replaceFirst("[.][^.]+$", "");
        String output = Character.toUpperCase(name.charAt(0)) + name.substring(1);
        writer.println(packageName);
        writer.println("public class " + output);
        writer.println("{");
        for (String obj : mArrayList) {
            writer.println("public String  " + obj + "=\"" + obj + "\";");
        }
        writer.println("}");
        writer.close();
    }

Upvotes: 1

Views: 2034

Answers (2)

Satheesh Cheveri
Satheesh Cheveri

Reputation: 3679

I have used FreeMarker templates to generate java source file. This is very powerful tool which allows you define a source template and and model where you can define variables, methods and every thing and allow you to compile to to any multiple format(txt, java,etc)

You can start by defining template with placeholder for your required java source,file and then later you can programatically apply the values for placeholder.

Given example illustrate the working of this API, you can extend the example to create java source file http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/

Upvotes: 1

Pradeep Simha
Pradeep Simha

Reputation: 18123

Yes, there is better way. Use CodeModel to create Java files programmatically, instead of using println() or String appending methods. From their website:

CodeModel is a Java library for code generators; it provides a way to generate Java programs in a way much nicer than PrintStream.println(). This project is a spin-off from the JAXB RI for its schema compiler to generate Java source files.

But the main problem with CodelModel is very less documentation. API docs is the only bible you can have for this.

If you are comfortable with Eclipse plugin development, you can use Eclipse's AST to create Java file programmatically. It can even work standalone without having Eclipse.

Upvotes: 4

Related Questions