java - 这是创建 java 文件(以编程方式)的正确方法吗?

标签 java

下面是以编程方式创建java文件的代码

这是正确的方法吗?或者有没有其他办法

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();
    }

最佳答案

是的,有更好的方法。使用 CodeModel以编程方式创建 Java 文件,而不是使用 println() 或 String 附加方法。来自他们的网站:

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.

但 CodelModel 的主要问题是文档太少。 API 文档是您可以拥有的唯一圣经。

如果您熟悉 Eclipse 插件开发,可以使用 Eclipse's AST以编程方式创建 Java 文件。它甚至可以在没有 Eclipse 的情况下独立工作。

关于java - 这是创建 java 文件(以编程方式)的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494442/

相关文章:

java - vector 和数组列表哪一个更好用?

java - 在java中打印垂直直方图时出现格式错误

java - Eclipse 错误, "The selection cannot be launched, and there are no recent launches"

java - 如何避免 forkjoin 延续造成的线程局部损坏

java - 什么是NumberFormatException,我该如何解决?

java - 在同一 Play Framework 项目中同时使用 Ebean 和 JPA

java - 如何确定当前运行的Play版本?

java - Eclipse gluon 新项目没有完成

java - 如何断言列表中的所有元素都在给定范围内

java - 如何从字符串中提取两个或多个字符?