//使用字节流读写
import java.io.*;
public class InOutputStream {
public static void main(String[] args){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
File file = new File("C:\\Users\\admin\\Desktop\\610.jpg");
File file1 = new File("C:\\Users\\admin\\Desktop\\611.jpg");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file1);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024];
int len;
while((len = bis.read(b))!=-1){
bos.write(b, 0, len);
bos.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(bos!=null){
try{
bos.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(bis!=null){
try{
if(bis!=null){
bis.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
//使用字符流(只适用于纯文本文件)
import java.io.*;
public class ReaderWriter {
public static void main(String[] args){
BufferedReader br = null;
BufferedWriter bw = null;
try{
File file = new File("C:\\Users\\admin\\Desktop\\aaa.txt");
File file1 = new File("C:\\Users\\admin\\Desktop\\bbb.txt");
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(file1);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
char[] c = new char[1024];
int len;
while((len=br.read(c))!=-1){
bw.write(c, 0, len);
bw.flush();
}
/*此方式会损失数据,不建议使用,建议使用上面的方式
* String str;
while((str=br.readLine())!=null){
bw.write(str+"\n");
bw.flush();
}*/
}catch(Exception e){
e.printStackTrace();
}finally{
if(bw!=null){
try{
bw.close();
}catch(Exception e){
}
}
if(br!=null){
try{
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
io流操作之读写示例代码(一)
最新推荐文章于 2021-12-11 22:07:29 发布