Friday 1 April 2016

java - How do I write a code template for eclipse?




I have some specific code that I need, to be able to have certain I/O stuff that I don't want to write every time, and I just want to be able to add a java class so that it already has that code in there, I tried doing :




/*
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) {


}
}


Basically this thing needs to be in xml, but I don't know how to write it properly, I thought writing ${filename} everywhere would do it, but it doesn't work. All in all, I want the name of the file to be written in places where I write "${filename}", how can I do it?


Answer



You can declare a template variable like this:



public class ${cursor}${type:newName} {

public ${type}() {
// constructor
}
}


Now if you use this as a template, both type occurrences will be updated by what you write when you edit it after template insertion.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...