Program to demonstrate how to read a file contents and convert it to String using Apache commons-io API in Java.

package com.hubberspot.apache.commons.examples;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class FileContentsToString {
public static void main(String[] args) {
// Create a File object and pass name of the file along
// with its path whose contents is to be read
File file = new File("C:/Program Files/glassfish-3.1.2/glassfish/domains/" +
"domain1/logs/server.log");
try {
// org.apache.commons.io package has a class by name
// FileUtils which has a method called as readFileToString()
// This method takes in a file object and return back
// contents of file in the form of String representing
// file contents as a String object
String fileContents = FileUtils.readFileToString(file);
// In order to print the contents of file on the console
// we just print the it on the console using
// System.out.println(String)
System.out.println(fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program to demonstrate how to read a file contents line by line using commons-io API in Java.

package com.hubberspot.apache.commons.examples;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class ReadFileLineByLine {
public static void main(String[] args) {
// Create a File object and pass name of the file along
// with its path whose contents is to be read
File file = new File("C:/Program Files/glassfish-3.1.2/glassfish/domains/" +
"domain1/logs/server.log");
try {
// org.apache.commons.io package has a class by name
// FileUtils which has a method called as readLines()
// This method takes in a file object and return back
// contents of file in the form of List representing
// each line as String object
List fileContents = FileUtils.readLines(file);
// In order to print the contents of file on the console
// we use for loop which iterates over List line by line
// and prints on the console.
for (String line : fileContents) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero in Java.