referance:
http://www.javapractices.com/topic/TopicAction.do?Id=42
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader in = new InputStreamReader(fis, "UTF-8");
FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
Scanner scanner = new Scanner(file, "UTF-8");
Example 1 - JDK 7+
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;
public class ReadWriteTextFileJDK7 {
public static void main(String... args) throws IOException{
ReadWriteTextFileJDK7 text = new ReadWriteTextFileJDK7();
//treat as a small file
List
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("Down to the Waterline", "Water of Love");
text.writeLargerTextFile(OUTPUT_FILE_NAME, lines);
}
final static String FILE_NAME = "C:\\Temp\\input.txt";
final static String OUTPUT_FILE_NAME = "C:\\Temp\\output.txt";
final static Charset ENCODING = StandardCharsets.UTF_8;
//For smaller files
/**
Note: the javadoc of Files.readAllLines says it's intended for small
files. But its implementation uses buffering, so it's likely good
even for fairly large files.
*/
List readSmallTextFile(String fileName) throws IOException {
Path path = Paths.get(fileName);
return Files.readAllLines(path, ENCODING);
}
void writeSmallTextFile(List lines, String fileName) throws IOException {
Path path = Paths.get(fileName);
Files.write(path, lines, ENCODING);
}
//For larger files
void readLargerTextFile(String fileName) throws IOException {
Path path = Paths.get(fileName);
try (Scanner scanner = new Scanner(path, ENCODING.name())){
while (scanner.hasNextLine()){
//process each line in some way
log(scanner.nextLine());
}
}
}
void readLargerTextFileAlternate(String fileName) throws IOException {
Path path = Paths.get(fileName);
try (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 fileName, List lines) throws IOException {
Path path = Paths.get(fileName);
try (BufferedWriter writer = Files.newBufferedWriter(path, ENCODING)){
for(String line : lines){
writer.write(line);
writer.newLine();
}
}
}
private static void log(Object msg){
System.out.println(String.valueOf(msg));
}
}
Example 2 - JDK 7+
This example demonstrates using Scanner to read a file containing lines of structured data. One Scanner is used to read in each line, and a second Scanner is used to parse each line into a simple name-value pair. The Scanner class is only used for reading, not for writing.
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Scanner;
/** Assumes UTF-8 encoding. JDK 7+. */
public final class ReadWithScanner {
public static void main(String... args) throws IOException {
ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
parser.processLineByLine();
log("Done.");
}
/**
Constructor.
@param fileName full name of an existing, readable file.
*/
public ReadWithScanner(String fileName){
filePath = Paths.get(fileName);
}
/** Template method that calls {@link #processLine(String)}. */
public final void processLineByLine() throws IOException {
try (Scanner scanner = new Scanner(filePath, ENCODING.name())){
while (scanner.hasNextLine()){
processLine(scanner.nextLine());
}
}
}
/**
Overridable method for processing lines in different ways.
This simple default implementation expects simple name-value pairs, separated by an
'=' sign. Examples of valid input:
height = 167cm
mass = 65kg
disposition = "grumpy"
this is the name = this is the value
*/
protected void processLine(String line){
//use a second Scanner to parse the content of each line
try(Scanner scanner = new Scanner(line)){
scanner.useDelimiter("=");
if (scanner.hasNext()){
//assumes the line has a certain structure
String name = scanner.next();
String value = scanner.next();
log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()));
}
else {
log("Empty or invalid line. Unable to process.");
}
}
}
// PRIVATE
private final Path filePath;
private final static Charset ENCODING = StandardCharsets.UTF_8;
private static void log(Object object){
System.out.println(Objects.toString(object));
}
private String quote(String text){
String QUOTE = "'";
return QUOTE + text + QUOTE;
}
}
Example run of this class:
Name is : 'height', and Value is : '167cm'
Name is : 'mass', and Value is : '65kg'
Name is : 'disposition', and Value is : '"grumpy"'
Name is : 'this is the name', and Value is : 'this is the value'
Done.
Yorumlar
Yorum Gönder