Most of us, who have worked on eclipse IDE for writing code, must have used shortcuts like main or sysout and then hit CTRL+SPACE, which converts the shortcut into public static void main(String[] args){…} and System.out.println() respectively. This is an extremely useful feature, and I use it all the time whenever I am writing code for my project or tutorials.
The 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 an XML string passed as a parameter. The code to parse such XML string is always almost the same. We can create a template for it and then use a shortcut for it whenever needed.
1. How to Create and Use a New Template
To create the shortcut for XML string parsing, follow the below steps:
- Open your Preferences dialog by going to ‘Windows -> Preferences‘
- On the navigation tree on the left, go to ‘Java -> Editor -> Templates‘
- You will see a list of pre-defined templates
- Add a new template by pressing the “New…” button
- Fill in the template information as given below and save it
- Use the template in any java source file using CTRL+SPACE
- Hit Enter, and it will generate the code below. Enjoy !!
You see how useful it can be. Now let’s note down some code templates which you can use directly.
2. Useful Templates for Common Usecases
2.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 close files automatically. They also use methods from NIO2.0 to obtain a buffered reader and read the file.
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
}
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}
Write to 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.2. XML I/O Templates
The following templates are used to read xml files or strings and return a DOM.
Parse an 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}
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}
2.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.
Create a new Logger
${:import(org.slf4j.Logger,
org.slf4j.LoggerFactory)}
private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class);
Check Debug scope before putting debug log
if(LOGGER.isDebugEnabled())
LOGGER.debug(${word_selection}${});
${cursor}
Log info level statement
LOGGER.info(${word_selection}${});
${cursor}
Log the error
LOGGER.error(${word_selection}${}, ${exception_variable_name});
Log error and throw an exception
LOGGER.error(${word_selection}${}, ${exception_variable_name});
throw ${exception_variable_name};
${cursor}
2.4. JUnit Templates
Junit before method
${:import (org.junit.Before)}
@Before
public void setUp() {
${cursor}
}
Junit after method
${:import (org.junit.After)}
@After
public void tearDown() {
${cursor}
}
Junit before class
${:import (org.junit.BeforeClass)}
@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
${cursor}
}
Junit after class
${:import (org.junit.AfterClass)}
@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
${cursor}
}
3. Resources
Please note that these templates can be defined for other file types such as XML, JSPs etc. More templates can be found here in the given links.
- https://stackoverflow.com/questions/1028858/seeking-useful-eclipse-java-code-templates
- https://www.eclipse.org/pdt/help/html/using_templates.htm
Happy Learning !!
Comments