学习io流-1

来源:互联网 发布:国内实时数据库 编辑:程序博客网 时间:2024/05/16 15:43
age com.hp.p1;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class demo1 {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
 * 举例


File f=new File("D:\\msdia80.dll");//输入流,把文件里的信息打印到控制台上
FileInputStream fis=null;//定义成全局的可以让下面的可以让finally获取到
try {
fis=new FileInputStream(f);
 
byte[] b=new byte[1024];//定义一个byte类型的数组,数组长度为1024,最多可存1024个字节的东西,如果超过就会报溢出的异常
int a=fis.read(b);
while(a!=-1){//给个判断
String str=new String(b,0,a);//下标  从哪里开始读到哪里
a=fis.read(b);
System.out.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(fis!=null){
fis.close();//关闭流
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

 */

// File f=new File("D:\\msdia80.dll");//复制  把D盘复制到C盘
// File ff=new File("C:\\新建文本文档.txt");
// FileInputStream fis=null;
// FileOutputStream fos=null;
// try {
// fis=new FileInputStream(f);
//  fos=new FileOutputStream(ff);
//  int a=fis.read();
//  while(a!=-1){
//  fos.write(a);
//  
//  }
// } catch (FileNotFoundException e) {//Exception异常表示一种设计或实现问题,也就是说,它表示如果程序运行异常,从不会发生的情况
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// finally{
// try {
// if(fos!=null){
// fos.close();
// }
// if(fis!=null){
// fis.close();
// }
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }

File ff=new File("C:\\新建文本文档1.txt");
FileOutputStream fos=null;//输出流
try {
fos=new FileOutputStream(ff);
String str="你好中国!";//写个字符串把它输到文本文档中
byte[] b=str.getBytes();//getBytes()方法是得到一个操作系统默认的编码格式的字节数组
fos.write(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(fos!=null){
fos.close();
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
原创粉丝点击