I/O流的一些知识

 

1创建文件

 File ff=new File("1.txt");//创建文件

 ff.createNewFile();
 
 
 File f2=new File("sss");
 ff.mkdir();//创建单个文件夹
 
 File f3=new File("sss/sss/sss");

 f3.mkdirs();//创建多重文件夹



2文件字节流FileInputStream类与FileOutputStream类


File file= new File("C:/test/word1.txt");
FileOutputStream out=null;
try {
out=new FileOutputStream(file,false);//文件输出流file后加true 则在文件末尾添加内容
                                     //加false  则替换文件内容
String str="天王盖地虎,玉帝日王母";
byte brr[]=str.getBytes();
out.write(brr);

} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}


//  输入流


FileInputStream in=null;
try {
in =new FileInputStream(file);//输入流读文件
byte brr2[]=new byte[111];//缓冲区
int a=in.read(brr2);//读入缓冲区的总字节数
System.out.println("文件中的数据为:"+new String(brr2,0,a));//去掉空格


} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}


3.文件字符流FileReader类与FileWriter类


File file= new File("C:/test/word5.txt");
FileWriter out=null;
try {
out=new FileWriter(file);//字符输出流file后加true 则在文件末尾添加内容
                                     //加false  则替换文件内容
String str="宝塔镇河妖,段友吊缠腰";

out.write(str);//将字符串写入文本文档

} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}


// 字符 输入流


FileReader in=null;
try {
in =new FileReader(file);//输入流读文件
char[] ch=new char[1024];//缓冲区
int count   ;             //已经读出的字符数
while((count=in.read(ch))!=-1) {//循环读出文档中的数据   知道所有字符都读完
System.out.println("文件中的数据为:"+new String(ch,0,count));
}


} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值