Monday, 7 October 2013

Read File Using Java 1.7 Files Class


import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;

//Files class is available from 1.7
public class FilesClassExample {

public static void main(String args[]){
Path path = Paths.get("d:/ram.txt");
        
        try {
               /*
                //Read file to byte array
byte[] bytes = Files.readAllBytes(path);

String val=new String(bytes);
System.out.println(val);

*/

//Read file to String list
               List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
      
      Iterator<String> i=allLines.iterator();
      while(i.hasNext()) {
          System.out.println(i.next());
      }
      
} catch (IOException e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment