// Note: try-with-resources is available from JDK 7
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
final String fileName = "d:\\Test.java";
System.out.println(readFile01(fileName));
System.out.println(readFile02(fileName));
System.out.println(readFile03(fileName));
}
public static String readFile01(String fileName) throws IOException {
FileReader fileReader = new FileReader(new File(fileName));
BufferedReader bufferedReader = new BufferedReader(fileReader);
String data = null;
try {
data = bufferedReader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
return data;
}
public static String readFile02(String fileName) throws IOException {
FileReader fileReader = new FileReader(new File(fileName));
String data = null;
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
data = bufferedReader.readLine();
}
return data;
}
public static String readFile03(String fileName) throws IOException {
FileReader fileReader01 = new FileReader(new File(fileName));
FileReader fileReader02 = new FileReader(new File(fileName));
String data = null;
try (BufferedReader bufferedReader01 = new BufferedReader(fileReader01);
BufferedReader bufferedReader02 = new BufferedReader(
fileReader02)) {
data = new StringBuilder(bufferedReader01.readLine()).append(
bufferedReader02.readLine()).toString();
}
return data;
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.