字节缓冲流: BufferedInputStream和BufferOutputStream
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class BuffInput {
public static void main(String[] args) {
File src=new File("a.txt");
InputStream is=null;
try {
is=new BufferedInputStream(new FileInputStream(src));
byte[] flush=new byte[1024];
int len=-1;
while((len=is.read(flush))!=-1) {
String str=new String(flush,0,len);
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
用法就是将FileInputStream嵌套如Buffer中,可以起到提高性能缓冲的作用,但仅限于纯文本
/*文件拷贝步骤+buffer 仅限于纯文本
* 1.创建源(输入和输出)
* 2.选择流
* 3.操作
* 4.释放资源
*/
public class BufferCopy {
public static void main(String[] args) {
copy("a.txt","b.txt");
}
public static void copy(String srcPath,String destPath) {
//源
File a=new File(srcPath);
File b=new File(destPath);
//输出流和输入流
try (BufferedReader br=new BufferedReader(new FileReader(a));
BufferedWriter bw=new BufferedWriter(new FileWriter(b));){
//操作:逐行读取
String line=null;
while((line=br.readLine())!=null) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
三个过程 IuputStream->InputStreamReader->BufferInputStream(OutputStream也差不多)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
/*
* 转换流:InputStreamReader和OutputStreamWriter
* 1.以字符流形式操作字节流(纯文本)
* 2.指定字符集
*/
public class ConvertTest2 {
public static void main(String[] args) {
//操作网络流:下载百度的网络流
try(BufferedReader is=new BufferedReader
(new InputStreamReader
(new URL("http://www.baidu.com").openStream(),"UTF-8"));
BufferedWriter os=new BufferedWriter
(new OutputStreamWriter
(new FileOutputStream("baidu.html"),"UTF-8"));){
String line=null;
while((line=is.readLine())!=null) {
//System.out.print(line);
os.write(line);//字符集不统一乱码
os.newLine();
}
}catch(IOException e) {
System.out.println("操作异常");
}
}
public static void test(String[] args) {
//操作网络流:下载百度的网络流
try(InputStream is=new URL("http://www.baidu.com").openStream();){
int temp;
while((temp=is.read())!=-1)
System.out.print((char)temp);//字节数不够乱码
}catch(IOException e) {
System.out.println("操作异常");
}
}
public static void test2(String[] args) {
//操作网络流:下载百度的网络流
try(InputStreamReader is=new InputStreamReader(new URL("http://www.baidu.com").openStream(),"UTF-8");){
int temp;
while((temp=is.read())!=-1)
System.out.print((char)temp);
}catch(IOException e) {
System.out.println("操作异常");
}
}
}