java字节流

java字节流

public class HelloWorld {

    public static void main(String[] args) {
        // [1] 指定要保存的路径
        String path = "d:\\aaa\\test.txt";
        // 输出文件内容
        outputFile(path, "nimeiadzcxzcdaaaaae");
        // 获取文件内容
        String result = inputFile(path);
        System.out.println("读取结果" + result);
        // 删除文件
        //delFile(path);
    }

    /**
     * 获取文件内容
     * @param saveFilePath 要读取的文件位置
     * @return 读取到的字符串
     */
    private static String inputFile(String saveFilePath) {
        File file = new File(saveFilePath);
        if(!file.exists()){
            // 判断文件是否存在
            return "文件不存在";
        }
        FileInputStream fis = null;
        StringBuffer sb = null;
        try {
            //  创建一个输入流
            fis = new FileInputStream(file);
            sb = new StringBuffer();
            int len = 0;
            // 创建字节数组用于存放临时的数据
            byte[] b = new byte[1024];
            while (-1 != (len = fis.read(b))) {
                String s = new String(b, 0, len);
                sb.append(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 输出内容到文件
     * @param saveFilePath 文件的保存路径
     * @param saveStr 要写入的字符串
     */
    private static void outputFile(String saveFilePath, String saveStr) {
        // 根据指定路径创建文件
        File file = new File(saveFilePath);
        // 获取文件的父路径
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            // 路径不存在则创建路径
            parentFile.mkdirs();
        }
        // 将字符串转换成字节数组
        byte[] bytes = saveStr.getBytes();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void delFile(String saveFilePath){
        File file = new File(saveFilePath);
        // 删除文件
        file.delete();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值