如何为eclipse编写代码模板?

时间:2016-03-03 22:38:04

标签: java eclipse

我有一些我需要的特定代码,能够拥有我不想每次都写的某些I / O内容,而我只想添加一个java类,以便它已经有了那里的代码,我尝试过:

/*
ID: my_id
PROG: ${filename}
LANG: JAVA
 */
import java.util.*;
import java.io.*;
import java.net.InetAddress;

public class ${filename} {

    static class InputReader {
        private StringTokenizer st = null;
        private BufferedReader br = null;

        public InputReader(String fileName) throws Exception {
            try {
                br = new BufferedReader(new FileReader(fileName));
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

        public InputReader(InputStream in) {
            try {
                br = new BufferedReader(new InputStreamReader(in), 32768);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

        public String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }

    public static void main(String[] args) throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();
        boolean isLocal = hostname.equals("paulpc");
        String location = null;
        InputReader in = null;
        PrintWriter out = null;
        if (!isLocal) {
            location = ${filename}.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            in = new InputReader(location + "/" + "${filename}.in");
            out = new PrintWriter(new FileWriter(location + "/" + "${filename}.out"));
        } else {
            in = new InputReader(System.in);
            out = new PrintWriter(System.out);
        }
        solve(in, out);
        out.close();
    }

    public static void solve(InputReader in, PrintWriter out) {

    }
}

基本上这个东西需要在xml中,但是我不知道如何正确编写它,我认为在任何地方编写$ {filename}都会这样做,但它不起作用。总而言之,我希望将文件的名称写在我写“$ {filename}”的地方,我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

您可以声明一个模板变量:

public class ${cursor}${type:newName} {
    public ${type}() {
        // constructor
    }
}

现在,如果您将此作为模板使用,则在模板插入后编辑时,所有type次出现都会更新。