以前对Java IO中的装饰模式搞得稀里糊涂的,现在整理下它的使用方法如下:
文本文件的读写:
写文件
输出的一般模式:
PrintWriter
→BufferedWriter(可选项)
→FileWriter
PrintWriter out = new PrintWriter(file);
或者
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
创建添加式文本输出
PrintWriter out = new PrintWriter(file,true);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
下面看一个例子:
package com.tzy.file;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class TextFileWriter {
public static void main(String[] args) {
short age = 24;
String name = "tanzhenyu";
String gender = "male";
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("DataWriter.txt",true)));
out.println(name);
out.println(gender);
out.println(age);
out.close();
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Success!");
}
}
读文件
输入的一般模式:
BufferedReader
→FileReader
BufferedReader in = new BufferedReader(new FileReader(file));
下面看一个例子:
package com.tzy.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TextFileReader {
public static void main(String[] args) {
String filePath = "E:\EclipseWorkSpace\javaLang\";
String fileName = "DataWriter.txt";
try {
File myFile = new File(filePath,fileName);
BufferedReader in = new BufferedReader(new FileReader(myFile));
String line = in.readLine();
while (line != null) {
System.out.println(line);
line = in.readLine();
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
二进制文件的读写:
输入
进行二进制文件输入操作的一般模式为:
DataOutputStream
→BufferedOutputStream(可选项;推荐使用)
→FileOutputStream
DataOutputStream out = new DataoutputStream(new BufferedOutputStream(new FileOutputStream(file)));
输入
进行二进制文件读入操作的一般模式为:
DataInputStream
→BufferedInputStream(可选项;推荐使用)
→FileInputStream
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));