package pritom; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: pritom * Date: 14/12/12 * Time: 9:28 AM * To change this template use File | Settings | File Templates. */ public class ReadWriteTextFileJDK7 { public static void main(String... aArgs) throws IOException { ReadWriteTextFileJDK7 text = new ReadWriteTextFileJDK7(); //treat as a small file List<String> lines = text.readSmallTextFile(FILE_NAME); log(lines); lines.add("This is a line added in code."); text.writeSmallTextFile(lines, FILE_NAME); //treat as a large file - use some buffering text.readLargerTextFile(FILE_NAME); lines = Arrays.asList("Line added #1", "Line added #2"); text.writeLargerTextFile(OUTPUT_FILE_NAME, lines); } final static String FILE_NAME = "C:/tmp/input.txt"; final static String OUTPUT_FILE_NAME = "C:/tmp/output.txt"; final static Charset ENCODING = StandardCharsets.UTF_8; //For smaller files List<String> readSmallTextFile(String aFileName) throws IOException { System.out.print("***** readSmallTextFile *****\n"); Path path = Paths.get(aFileName); return Files.readAllLines(path, ENCODING); } void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException { System.out.print("***** writeSmallTextFile *****\n"); Path path = Paths.get(aFileName); Files.write(path, aLines, ENCODING); } //For larger files void readLargerTextFile(String aFileName) throws IOException { System.out.print("***** readLargerTextFile *****\n"); Path path = Paths.get(aFileName); Scanner scanner = new Scanner(path, ENCODING.name()); while (scanner.hasNextLine()){ //process each line in some way log(scanner.nextLine()); } } void readLargerTextFileAlternate(String aFileName) throws IOException { System.out.print("***** readLargerTextFileAlternate *****\n"); Path path = Paths.get(aFileName); BufferedReader reader = Files.newBufferedReader(path, ENCODING); String line = null; while ((line = reader.readLine()) != null) { //process each line in some way log(line); } } void writeLargerTextFile(String aFileName, List<String> aLines) throws IOException { System.out.print("***** writeLargerTextFile *****\n"); Path path = Paths.get(aFileName); BufferedWriter writer = Files.newBufferedWriter(path, ENCODING); for(String line : aLines){ writer.write(line); writer.newLine(); } writer.flush(); } private static void log(Object aMsg){ System.out.println(String.valueOf(aMsg)); } }
http://www.javapractices.com/topic/TopicAction.do?Id=42
No comments:
Post a Comment