一、写文件先创建文件,写入数据、关闭文件。
常用的流:FileOutputStream, OutputStreamWriter, bufferWriter(wtire和newLine)
try-resource语句,自动关闭资源(jad7以后可用,程序变得简洁)
要关闭最外层数据流,这样将会把其上所有数据流关闭
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"); // 转化类,写中文要用UTF-8//osw = new OutputStreamWriter(fos); // 转化类,不写是默认,一般是GBKbw = new BufferedWriter(osw); // 装饰类,缓存,增加写的速度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 语句,自动关闭资源,不用写finallly中的关闭了,比上边写起来简洁了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();
}
}
}
二、读文件先打开文件,逐行读入数据,最好关闭文件。
常用的流:FileIutputStream, IutputStreamWriter, bufferReader
BufferReader readLine()
try-resource语句,自动关闭资源,只关闭最外层的数据流即可,将会自动关闭其上所有的数据流
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);// 不写UTF-8,一般默认GBK
br = new BufferedReader(isr); // 装饰类
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 语句,自动关闭资源,不用自己写finally中的关闭
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();
}
}
}