Eclipse Tips and Tricks, Code Templates, Read File Line by Line

adevedo's picture
No votes yet

A template is a chunk of text or code that you can automatically insert into the file that you are working on in your editor using Eclipse's 'control-space' auto-completion feature.

Eclipse templates allow for quick generation of commonly used code, as well as easy customization, and as well as the ready set of custom templates already defined in Eclipse, Eclipse allows you to add your own templates

In this article we show how to create a new template that can be used to automatically generate the required lines to read file line by line

Assuming the following lines of codes

Step #1

Click the "Window" main menu, select the menu item "Preferences", Preferences dialog will show up

Step #2

From the Preferences dialog main tree, select "Java", then "Editor", then "Templates"

Step #3

Click the button "New...", the "Edit Template" dialog will show up, type in the name field "readFileLineByLine", and in the description field type "Read a file Line by Line", and in the pattern area, write the following lines - will be described later in the article

  1. ${:import(,}
  2. BufferedReader ${buffName} = new BufferedReader(new FileReader(${fileName}));
  3. String ${line} = null;
  4. while((${line} = ${buffName}.readLine()) != null) {
  5.         ${cursor}
  6. }
  7. ${buffName}.close();

Click the "Ok" button to close the "Edit Template" dialog

Step #4

Click the "Ok" button to close the "Preferences" dialog

Step #5

Now in the code editor window, type "read" then press Ctrl + Space bar to show the auto-complete dialog, the tempate "readFileLineByLine" will be in the top of the auto-complete list, eclipse will display the template body on the right side of the auto-complete list, Click "Enter" to select the template

Step #6

Eclipse will insert 2 sections of codes, #1, 2 import statements (,, use the Tab key to move between the templates variables - "buffName", "fileName" and "line" - and type new names if needed

The Final Code

Adding a statement to print the line (Your Logic), Now the final code will be as the following :

Template Description

  • Line #1: Import the 2 classes and
  • Line #2: Create a new BufferedReader Stream wrapping a FileReader Stream
  • Line #3: The Line holder
  • Line #4: Loop until end of line (Line Holder will be null)
  • Line #5: Put the cursor here after finishing variables typing
  • Line #6: End of loop body
  • Line #7: Close the BufferedReader Stream

You can also change the Template to use try, catch and finally blocks...

Add new comment

This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.
By submitting this form, you accept the Mollom privacy policy.