Eclipse Tips and Tricks, Code Templates, Read File Line by Line
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
Click the "Window" main menu, select the menu item "Preferences", Preferences dialog will show up
From the Preferences dialog main tree, select "Java", then "Editor", then "Templates"
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
Click the "Ok" button to close the "Edit Template" dialog
Click the "Ok" button to close the "Preferences" dialog
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
Eclipse will insert 2 sections of codes, #1, 2 import statements (java.io.BufferedReader, java.io.FileReader), 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 :
- Line #1: Import the 2 classes java.io.BufferedReader and java.io.FileReader
- 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...