标签:
/*此处实现文件读取
* IO流分类: 方向-----输入流,输出流
* 类型-----字节流,字符流
* 操作方式------节点流,过滤流
* 转换流
* */
public static void main(String[] args) {
InputStream in=null;
try {
//1.定义一个文件输入流
in=new FileInputStream("F:/我的分享.txt");
//2.定义一个字节数组用了存储读取的内容
byte[] buf=new byte[1024];
//3.使用len保存读取的长度
int len=0;
//4.循环读取直到len<0没有内容为止
while((len=in.read(buf))>=0){
//输出,必须说明输出的长度,原因参考缓冲区工作原理图
System.out.write(buf);
}
/*5.关闭IO流释放系统资源,如果上面发出异常,这句不会执行,
* 所以下面用finally执行
*/
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(in!=null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/////////////////////////////
/*节点流与过滤流,缓冲使用*/
public static void main(String[] args) {
InputStream in=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
in=new FileInputStream("D:\\系统\\服务器\\JSP7.0开发环境\\apache-tomcat-7.0.42-windows-x86.zip");
bis=new BufferedInputStream(in);
bos=new BufferedOutputStream(new FileOutputStream("F:/2/newTomcat.zip"));
byte[] buf=new byte[1024];
int len=0;
while((len=bis.read(buf))>=0){
bos.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bis!=null) bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bos!=null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//////////////////////////////
//文件输入流和文件输出流实现复制功能
public static void main(String[] args) {
InputStream in=null;
OutputStream ou=null;
try {
in=new FileInputStream("F:/文库格式.jpg");
ou=new FileOutputStream("D:/copy.bmp");
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))>=0){
ou.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(in!=null) in.close();
}catch(IOException e){e.printStackTrace();}
try{
if(ou!=null) ou.close();
}catch(IOException e){e.printStackTrace();}
}
}
标签:
原文地址:http://my.oschina.net/686991/blog/509004