import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
public class TxtFileRead {
public static void main(String[] args) {
readFile1();
System.out.println("===================");
//readFile2(); //JDK 7及以上才可以使用
}
public static void readFile1() {
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream("c:/temp/abc.txt"); // 节点类
isr = new InputStreamReader(fis, "UTF-8"); // 转化类
//isr = new InputStreamReader(fis);
br = new BufferedReader(isr); // 装饰类
// br = new BufferedReader(new InputStreamReader(new
// FileInputStream("c:/temp/abc.txt")))
String line;
while ((line = br.readLine()) != null) // 每次读取一行
{
System.out.println(line);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
br.close(); // 关闭最后一个类,会将所有的底层流都关闭
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void readFile2() {
String line;
//try-resource 语句,自动关闭资源
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("c:/temp/abc.txt")))) {
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
import java.io.*;
public class TxtFileWrite {
public static void main(String[] args) {
writeFile1();
System.out.println("===================");
//writeFile2(); // JDK 7及以上才可以使用
}
public static void writeFile1() {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream("c:/temp/abc.txt"); // 节点类
osw = new OutputStreamWriter(fos, "UTF-8"); // 转化类
//osw = new OutputStreamWriter(fos); // 转化类
bw = new BufferedWriter(osw); // 装饰类
// br = new BufferedWriter(new OutputStreamWriter(new
// FileOutputStream("c:/temp/abc.txt")))
bw.write("我们是");
bw.newLine();
bw.write("Ecnuers.^^");
bw.newLine();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
bw.close(); // 关闭最后一个类,会将所有的底层流都关闭
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void writeFile2() {
//try-resource 语句,自动关闭资源
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c:/temp/abc.txt")))) {
bw.write("我们是");
bw.newLine();
bw.write("Ecnuers.^^");
bw.newLine();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}