設置記憶體緩衝區 (預設 8KB),減少對磁碟的頻繁讀寫,大幅提升 IO 效率。
FileInputStreamFile file = new File("D:\\a.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int content;
while ((content = bis.read()) != -1) {
System.out.print((char) content);
}
bis.close();
flush()/close() 才寫入磁碟FileOutputStream fos = new FileOutputStream("D:\\b.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write("good good study day day up".getBytes());
bos.flush(); // 或 close() 會自動 flush
bos.close();
readLine() 一次讀取一行 (含換行符)FileReader fr = new FileReader("D:\\b.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
newLine() 跨平台換行FileWriter fw = new FileWriter("D:\\a.txt", true); // true = 附加模式
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.write("上課不要吃東西");
bw.close(); // 關閉前自動 flush
public class BufferedByteDemo {
public static void main(String[] args) throws IOException {
copyFile("D:\\source.txt", "D:\\target.txt");
}
public static void copyFile(String src, String dest) throws IOException {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest))) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
}
}
}
public class BufferedCharDemo {
public static void main(String[] args) throws IOException {
writeLines();
readLines();
}
static void writeLines() throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\lines.txt"))) {
bw.write("第一行"); bw.newLine();
bw.write("第二行"); bw.newLine();
}
}
static void readLines() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader("D:\\lines.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}