Create Eclipse Templates for Faster Java Coding

Most of us who have worked on eclipse IDE for writing code, must have use shortcuts like main or sysout and then hit CTRL+SPACE, it converts the shortcut into public static void main(String[] args){…} and System.out.println() respectively. This is extremely useful feature and I use it all the time whenever I am writing code for my project or tutorials.

Good news is you can add your own templates as well in this list and take benefit of this feature. e.g. there is a very common requirement of parsing a XML string passed as parameter. The code to parse such XML string is always almost same. We can create a template for it and then use a shortcut for it whenever needed.

How to create new eclipse templates

To create the shortcut for XML string parsing, follow below steps:

1) Open your Preferences dialog by going to
Windows -> Preferences
2) On the navigation tree on the left, go to Java -> Editor -> Templates
3) You will see a list of pre-defined templates

Eclipse Predefined Templates
Eclipse Predefined Templates

4) Add a new template by pressing the “New…” button
5) Fill the template information as given below and save it

Create New Template
Create New Template

6) Use the template in any java source file using CTRL+SPACE

Use template Shortcut
Use template Shortcut

7) Hit Enter and it will generate the code a below. Enjoy !!

Code inserted in place of shortcut
Code inserted in place of shortcut

You see how useful it can be. Now let’s note down some code templates which you can use directly.

Useful Eclipse Templates Examples

1) File IO Templates

The following templates are useful for reading or writing files. They use Java 7 features such as try-with-resources to automatically close files. They also use methods from NIO2.0 to obtain a buffered reader and read the file.

a) To read the text from a file

${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.charset.Charset,
          java.io.IOException,
          java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
                                                 Charset.forName("UTF-8"))) {
    String line = null;
    while ((line = in.readLine()) != null) {
        ${cursor}
    }
} catch (IOException e) {
    // ${todo}: handle exception
}

b) Read all lines from a file in a list

${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.charset.Charset,
          java.util.List,
          java.util.ArrayList)}
Lis<String> lines = new ArrayList<>();
try{
    lines = Files.readAllLines(Paths.get(${fileName:var(String)}),
                                        Charset.forName("UTF-8"));
}catch (IOException e) {
    // ${todo}: handle exception
}
${cursor}

c) Write into a file

${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.Charset,
          java.io.IOException,
          java.io.BufferedWriter)}
try (BufferedWriter out = Files.newBufferedWriter(Paths.get(${fileName:var(String)}),
                                                  Charset.forName("UTF-8"))) {
    out.write(${string:var(String)});
    out.newLine();
    ${cursor}
} catch (IOException e) {
    // ${todo}: handle exception
}

2) XML I/O Templates

The following templates are used to read xml files or strings and return a DOM.

a) Parse a XML file into Document

${:import(org.w3c.dom.Document,
          javax.xml.parsers.DocumentBuilderFactory,
          java.io.File,
          java.io.IOException,
          javax.xml.parsers.ParserConfigurationException,
          org.xml.sax.SAXException)}
Document doc = null;
try {
    doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new File(${filename:var(String)}));
} catch (SAXException | IOException | ParserConfigurationException e) {
    // ${todo}: handle exception
}
${cursor}

b) Parse XML string as Document

${:import(org.w3c.dom.Document,
          javax.xml.parsers.DocumentBuilderFactory,
          org.xml.sax.InputSource,
          java.io.StringReader,
          java.io.IOException,
          javax.xml.parsers.ParserConfigurationException,
          org.xml.sax.SAXException)}
Document doc = null;
try {
    doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new InputSource(new StringReader(${str:var(String)})));
} catch (SAXException | IOException | ParserConfigurationException e) {
    // ${todo}: handle exception
}
${cursor}

3) Logging Templates

The templates below are useful for creating a logger and logging messages. I use SLF4J, but they could easily be tweaked to use any other logging framework.

a) Create a new Logger

${:import(org.slf4j.Logger,
          org.slf4j.LoggerFactory)}
private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class);

b) Check Debug scope before putting debug log

if(LOGGER.isDebugEnabled())
     LOGGER.debug(${word_selection}${});
${cursor}

c) Log info level statement

LOGGER.info(${word_selection}${});
${cursor}

d) Log the error

LOGGER.error(${word_selection}${}, ${exception_variable_name});

e) Log error and throw exception

LOGGER.error(${word_selection}${}, ${exception_variable_name});
throw ${exception_variable_name};
${cursor}

4) JUNIT Templates

a) Junit before method

${:import (org.junit.Before)}
 
@Before
public void setUp() {
    ${cursor}
}

b) Junit after method

${:import (org.junit.After)}
 
@After
public void tearDown() {
    ${cursor}
}

c) Junit before class

${:import (org.junit.BeforeClass)}
 
@BeforeClass
public static void oneTimeSetUp() {
    // one-time initialization code
    ${cursor}
}

d) Junit after class

${:import (org.junit.AfterClass)}
 
@AfterClass
public static void oneTimeTearDown() {
    // one-time cleanup code
    ${cursor}
}

Please note that these templates can be defined for other file types such as XML, JSPs etc. More templates can be found here in given links:

http://stackoverflow.com/questions/1028858/useful-eclipse-java-code-templates
https://www.eclipse.org/pdt/help/html/using_templates.htm

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial