1.缓冲流
使用缓冲流实现a.jpg文件复制为b.jpg文件的操作
public class Exer01 {
public static void main(String[] args) {
String src = "/exer01/a.jpg" ;
String dest = "/exer01/b.jpg" ;
bufferedCopyFile(src,dest);
}
public static void bufferedCopyFile(String src , String dest){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dest));
byte[] data = new byte[1024];
int length ;
while ((length = bis.read(data)) != -1){
bos.write(data,0,length);
}
System.out.println("文件复制成功");
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if (bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2. 转换流
将gbk格式的文件转换为utf-8格式存储
public class GBKToUTF_8 {
@Test
public void test() {
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
isr = new InputStreamReader(new FileInputStream(new File("test.txt")),"GBK");
osw = new OutputStreamWriter(new FileOutputStream(new File("test_copy.txt")), "UTF-8");
char[] cbuf = new char[8192];
int len;
while ((len = isr.read(cbuf)) != -1) {
osw.write(cbuf, 0, len);
}
System.out.println("格式转换成功<GBK → UTF-8>");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (osw != null)
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}