Monday, December 3, 2012

Read file content with Java (+ Maven )

Simple way to get the file content using java, get it now:

1. Standard Java way to read the file content. There are two methods for different Java versions. readFileJav6 is appropriate for Java 7 as well, but I'd like to recommend you to improve it with new try-with-resources block (see more: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)

public List<String> readFileJava7(String filename) {
 List<String> content = new LinkedList<String>();
 Path filePath = Paths.get(filename);
 try {
  content = Files.readAllLines(filePath, Charset.defaultCharset());
  //OR
  // String contents = new String(Files.readAllBytes(
Paths.get("alice.txt")), StandardCharsets.UTF_8);
 } catch (IOException e) {
  System.out.println("Unable to read the file " + filename);
 }
 return content;
}

public List<String> readFileJava6(String filename) {
 List<String> content = new LinkedList<String>();
 FileReader fr;
 BufferedReader br = null;
 try {
  fr = new FileReader(filename);
  br = new BufferedReader(fr);
  String output;
  while ((output = br.readLine()) != null) {
   content.add(output);
  }
 } catch (FileNotFoundException e) {
  System.out.println("Unable to find the file " + filename);
 } catch (IOException e) {
  System.out.println("Unable to read the file " + filename);
 } finally {
  try {
   br.close();
  } catch (IOException e) {
   System.out.println("Couldn't close the file " + filename);
  }
 }
 return content;
}

2. Apache Commons IO

String content = IOUtils.toString(new FileReader("file.txt"), "utf-8");


<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-io</artifactId>
 <version>1.3.2</version>
</dependency>


 

3. Google Guava

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);


<dependency>
 <groupId>com.google.guava</groupId>
 <artifactId>guava</artifactId>
 <version>r05</version>
</dependency> 

No comments:

Post a Comment