FileInputStream和FileOutputStream

绝对路径和相对路径:
绝对路径一般从根目录开始,写全路径
相对路径一般从当前目录开始

FileInputStream

读文件的流程:
1、FileInputStream对象和String结果对象声明
2、创建FileInputStream对象(文件路劲或File对象)
3、读单字节或整个读到byte数组中
4、转成字符串
5、关闭FileInoutStream流
6、返回结果字符串

public static String readFile(String path){
//        File f=new File(path);
        FileInputStream fis=null;
        String str=null;
        try {
            fis = new FileInputStream(path);
            byte[] b=new byte[fis.available()];
//            byte[] rst=null;
            fis.read(b);
//            for (int i = 0; i < b.length; i++) {
//                if (b[i]==0)
//                    rst=Arrays.copyOf(b,i);
//            }
            str=new String(b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }
 //单字节方法
    public static String readByOne(String path){
        FileInputStream fis=null;
        String str=null;
        try {
            fis=new FileInputStream(path);
            StringBuffer sb=new StringBuffer();
            int tmp;
            while ((tmp=fis.read())!=-1){//read读的是ASCLL码值
                char c= (char) tmp;
                sb.append(c);
            }
            str=sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
}

FileOutputStream

写文件的流程:
1、File对象转载文件路径
2、判断文件父级目录是否存在,不存在则创建
3、声明FileOutputStream对象
4、创建FileOutputStream对象(File对象,是否追加)
5、把要写的字符串转成byte数组,并写入输出流
6、关闭FileOutputStream流

public static void writeFile(String str,String path,boolean isAppend){
        File f=new File(path);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        FileOutputStream fos=null;
        try {
            fos=new FileOutputStream(f,isAppend);
            byte[] b=str.getBytes();
            fos.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值