IO流,图片、文件的拷贝:
package util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main
{
public static void main(String[] args)
{
new Main().copyFile("C:\\Users\\Desktop\\JVM.txt", "C:\\Users\\Desktop\\JVM1.txt");
new Main().copyPicture("C:\\Users\\Desktop\\aa.jpg", "C:\\Users\\Desktop\\bb.jpg");
}
/**
* 字节流拷贝图片
*/
public void copyPicture(String path1, String path2)
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
bis = new BufferedInputStream(new FileInputStream(path1));
bos = new BufferedOutputStream(new FileOutputStream(path2));
byte[] bs = new byte[10240];
int len = 0;
while((len = bis.read(bs)) != -1)
{
bos.write(bs, 0, len);
}
System.out.println("拷贝图片成功");
}
catch (FileNotFoundException e)
{
throw new RuntimeException(path1+" 文件不存在");
}
catch (IOException e)
{
throw new RuntimeException("拷贝图片失败");
}
finally
{
try
{
if(null != bis)
{
bis.close();
}
}
catch (IOException e)
{
throw new RuntimeException("bis关闭失败");
}
try
{
if(null != bos)
{
bos.close();
}
}
catch (IOException e)
{
throw new RuntimeException("bos关闭失败");
}
}
}
/**
* 字符流、字节流都可以拷贝文件
*/
public void copyFile(String path1,String path2)
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
//设置编码格式
//br = new BufferedReader(new InputStreamReader(new FileInputStream(path1),"UTF-8"));
//bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path2),"UTF-8"));
br = new BufferedReader(new FileReader(path1));
bw = new BufferedWriter(new FileWriter(path2));
int len = 0;
char[] cs = new char[10240];
while((len = br.read(cs)) != -1)
{
bw.write(cs, 0, len);
}
System.out.println("拷贝文件成功");
}
catch (FileNotFoundException e)
{
throw new RuntimeException(path1+" 文件不存在");
}
catch (IOException e)
{
throw new RuntimeException("拷贝文件失败");
}
finally
{
try
{
if(null != br)
{
br.close();
}
}
catch(IOException e)
{
throw new RuntimeException("br关闭失败");
}
try
{
if(null != bw)
{
bw.close();
}
}
catch(IOException e)
{
throw new RuntimeException("bw关闭失败");
}
}
}
}