Tuesday, July 21, 2009

Reading a Text File in Groovy Step 4

This post will show you how Groovy can simplify your code.

under your GroovyHelloWorld folder, create a folder called resource.

Under the resource folder, create a file call test.txt and add these lines:

this is a test1
this is a test2
this is a test3
this is a test4

If you want to read these lines from a text file in Java, this is how you would write it:

Create a new Java class under your com.groovy.home called TestFile.java.

In that file, paste the following code:


Make sure you change the path to the location of your test.txt file.

Reading a Text file in Java


package com.groovy.home;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestFile {

public static void main(String[] args)
{
BufferedReader br=null;
try{
br=new BufferedReader(new FileReader("C:\\Programming Tools\\eclipse\\workspace\\GroovyHelloWorld\\resource\\test.txt"));
String line=null;
while((line=br.readLine())!=null){
System.out.println(line);
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

When you run this code, you will see the lines of your text file print to your console.

In the HelloWorld.groovy file, paste this code in the main class.

Reading a Text File in Groovy


new File("C:\\Programming Tools\\eclipse\\workspace\\GroovyHelloWorld\\resource\\test.txt").eachLine{
line->println line
}


When you run this line of code, you will see the information in the text file print as well. However, Groovy only uses one line of code.


Go To Step 5

0 comments: