最近刚刚学习了I/O文件输入和输出,感觉要学的东西非常的多。。。
一步一个脚印,踏踏实实的写好每个程序。。
package com.sun.print;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyStream {
private String srcFileNames;// 源文件名称
private String destFileNames; // 目标文件名称
public void Copy() {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
FileInputStream fis = new FileInputStream(srcFileNames);// 读取源文件
bis = new BufferedInputStream(fis);// 读入缓存
int fileSize = 0;
FileOutputStream fos = new FileOutputStream(destFileNames);// 读取目标文件
bos = new BufferedOutputStream(fos);// 读出缓存
byte[] perByte = new byte[1024];
int readCount;
while ((readCount = bis.read(perByte)) != -1) {
bos.write(perByte, 0, readCount);
fileSize += readCount;
}
bos.flush();// 清空缓存
System.out.printf("文件大小:%d/n", fileSize);//读取文件大小
System.out.println("copy over !");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CopyStream cs = new CopyStream();
cs.setSrcFileNames("d://ha.jpg");//源文件为一张图片
cs.setDestFileNames("d://haha.jpg");//目标文件copy副本
cs.Copy();
}
public String getDestFileNames() {
return destFileNames;
}
public void setDestFileNames(String destFileNames) {
this.destFileNames = destFileNames;
}
public String getSrcFileNames() {
return srcFileNames;
}
public void setSrcFileNames(String srcFileNames) {
this.srcFileNames = srcFileNames;
}
}
字节流转化成字符流的代码:
package com.runwit.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
public class InputStreamReaderTest {
/**
* @param args
*/
public static void main(String[] args) {
if(args.length == 0)
return;
try {
/**
* 将字节流转换成字符流的过程.
*/
FileInputStream fis = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}