io中的字节缓冲流(BufferedInputstream()/BufferedOutputStream())
1,提升了性能
2,最底层是节点流
3,嵌套的时候只需要释放最外层的处理流,内部会自动释放节点流
package cn.io.com;
import java.io.*;
public class TestBuffered01 {
public static void main(String[] args) {
//字节缓冲流
File file = new File("abc.txt");
try (InputStream is =
new BufferedInputStream(new FileInputStream(file))){
byte[] bytes =new byte[1024];
int tmp;
while((tmp = is.read(bytes)) != -1) {
String str = new String(bytes,0,tmp);
System.out.println(str);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
String str = "i like you very much";
byte[] flush = str.getBytes();
os.write(flush,0,flush.length);
os.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if (os != null) {
os.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
io中的字符缓冲流(BufferedReader()/BufferedWriter())
这里需要注意的是有新增的方法,不需要发生多态,在BufferedReader里面有readLine按每一行读取,读不到返回空。在BufferedWriter里面有newLine换行
package cn.io.com;
import java.io.*;
public class TestBufferReader {
public static void main(String[] args) {
//字符缓冲输入流
File file = new File("abc.txt");
try(BufferedReader reader =
new BufferedReader(new FileReader(file))) {
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}catch(IOException e) {
e.printStackTrace();
}
//字符缓冲输出流
try(BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.append("为了有更好的明天,我们现在需要一起努力!!");
bw.newLine();
bw.append("明天的你会为今天努力的你而感到骄傲自豪");
bw.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
}
使用缓冲流进行拷贝(将缓冲流综合应用)
package cn.io.com;
import java.io.*;
public class TestBufferCopy {
public static void main(String[] args) {
copy("abc.txt","abcCopy.txt");
}
public static void copy(String srcPath,String destPath) {
File src = new File(srcPath);
File dest = new File(destPath);
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(src));
writer = new BufferedWriter(new FileWriter(dest));
String line = null;
while((line = reader.readLine()) != null) {
writer.append(line);
writer.newLine();
}
writer.flush();
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if (writer != null) {
writer.close();
}
}catch(IOException e) {
e.printStackTrace();
}
try {
if (reader != null) {
reader.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}