Monday, May 18, 2015

How to Read file's content as a String in java.

Some times we quickly want to pass the file content as String in java method or for unit testing..

Here are the one-line solution directly from my java utilities.

1. using java.util.Scanner ...

import java.util.Scanner;
import java.io.FileNotFoundException;

private static String readFileContentAsString(String fileNameWithPath) throws FileNotFoundException{
return new Scanner(new File(fileNameWithPath)).useDelimiter("\\Z").next();
}

2. using java.nio.*(java 7)....

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

private static String readFile(String path, Charset encoding)   throws IOException {
    return new String(Files.readAllBytes(Paths.get(path)), encoding);
}

3.using apache commons-io library.

import org.apache.commons.io.IOUtils;
private static String readFile(String path) throws IOException{
    return IOUtils.toString(new FileInputStream(new File(path)), "UTF-8");
}

4.using google guava library.

import com.google.common.base.Charsets;
import com.google.common.io.Files;

private static String readFile(String path) throws IOException{
  return  Files.toString(new File(path), Charsets.UTF_8);
}
           


Thanks for reading!!......

No comments:

Post a Comment