自动生成文件并上传OSS存储设计思路

一、生成测试用例

步骤一:在本地生成该文件夹

public static void main(String args[]) throws IOException {
        String s = "D:/Work1";
        //三个参数,第一个表示要创建文件的根目录,第二个表示创建文件的层次
        makeDir(s, 9);
    }

    //创建目录
    public static void makeDir(String path, int num1) throws IOException {
        //随机生成每层文件的个数
        int num2 = (int) (Math.random()*10);
        num1 -= 2;
        if (num1 == 1) {
            for (int i = 0; i < num2; i++) {
                File f = new File(path, getFileNameOrText());
                f.mkdirs();
                //调用随机次生成新文件
                for (int j = 0; j < (int) (Math.random()*10); j++) {
                    newFile(f.getPath());
                }
            }
        } else {
            for (int i = 0; i < num2; i++) {
                makeDir(new File(path, getFileNameOrText()).getPath(), num1 - 1);
                //先创建该文件夹用于创建文件
                File f = new File(path);
                f.mkdirs();
                //调用随机次生成新文件
                for (int j = 0; j < (int) (Math.random()*10); j++) {
                    newFile(f.getPath());
                }
            }
        }
    }

    //生成文件名字或内容随机且长度为10的字符串
    public static String getFileNameOrText() {
        UUID uuid = UUID.randomUUID();
        String str1 = uuid.toString().substring(0, 2);
        return str1;
    }

    //生成名字与内容随机的一个文件
    public static File newFile(String filePath) throws IOException {
        String fileName = getFileNameOrText()+".text";
        File file = new File(filePath,fileName);
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getFileNameOrText().getBytes());
        return  file;
    }

步骤二:遍历该文件夹并获取每一个文件的完整路径

public static void main(String[] args) throws FileNotFoundException {
        MyFileUtils.getAllFile("D:\\Work1");
    }

    /**
     * 获取所有的文件和文件夹
     * @param filepath 路径
     */
    public static void getAllFile(String filepath) throws FileNotFoundException {
        List<File> allFiles=new ArrayList<>();
        findFolder(new File(filepath),allFiles);
    }

    /**
     * 递归
     * @param file
     * @param allFiles
     */
    private static void findFolder(File file,List<File> allFiles) throws FileNotFoundException {
        if(file.isDirectory()){
            allFiles.add(file);
            File[] files= file.listFiles();
            for(File f:files){
                findFolder(f,allFiles);
            }
        }else{
            //将文件上传至oss(name为文件名,text为内容)
            String name = file.getPath();//上传至oss文件名
            String text = "";
            Scanner sc = new Scanner(new FileReader(file.getPath()));
            while (sc.hasNextLine()) {  //按行读取字符串
                text = sc.nextLine();
            }
            upOSS(name,text);
        }
    }

步骤三:使用文件流上传至阿里oss

    /**
     * 将文件上传至oss
     * @param name 文件名
     * @param text  内容
     */
    private static void upOSS(String name,String text){
        // Endpoint为华东1(杭州)
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "";
        String accessKeySecret = "";
        // Bucket名称
        String bucketName = "";
        //上传OSS时需要将\改为/
        name = update(name);
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = name;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(text.getBytes()));
            // 上传字符串。
            ossClient.putObject(putObjectRequest);
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    //将\改为/
    private static String update(String name) {
        return name.replace("\\","/");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kblzxj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值