下载之前,请先从Blob URL路径读取数据并将其追加到文件中

时间:2019-02-21 14:52:29

标签: java spring-boot java-io spring-restcontroller urlconnection

这是我第一次在项目中使用Java Spring引导,因为我最常使用C#,并且我需要从blob URL路径读取文件,并将一些字符串数据(如键)附加到同一位置在我的API下载文件之前,先将文件放入流中。

以下是我尝试执行的方法:

  1. FileOutputStream / InputStream :由于无法解析Blob路径,因此抛出FileNotfoundException。
  2. URLConnection :这使我获得了成功,我能够成功下载文件,但是当我尝试在下载之前向文件写入/附加一些值时,我失败了。

    我一直在做的代码。

        //EXTERNAL_FILE_PATH is the azure storage path ending with for e.g. *.txt
        URL urlPath = new URL(EXTERNAL_FILE_PATH);
        URLConnection connection = urlPath.openConnection();
        connection.setDoOutput(true); //I am doing this as I need to append some data and the docs mention to set this flag to true. 
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("I have added this");
        out.close();
    
    
        //this is where the issues exists as the error throws saying it cannot read data as the output is set to true and it can only write and no read operation is allowed. So, I get a 405, Method not allowed...
        inputStream = connection.getInputStream(); 
    

我不确定框架是否允许我修改URL路径中的某些文件并同时读取并下载。

请帮助我理解它们是否是一种更好的方法。

1 个答案:

答案 0 :(得分:0)

从逻辑的角度来看,您不是将数据从{em> URL添加到文件中。您需要创建新文件,写入一些数据,然后再添加URL中文件的内容。算法可能如下所示:

  1. 可以在磁盘上的File文件夹中创建新的TMP
  2. 将一些数据写入文件。
  3. URL下载文件,并将其附加到磁盘上的文件中。

一些好的文章,您可以从它们开始:

  1. Download a File From an URL in Java
  2. How to download and save a file from Internet using Java?
  3. How to append text to an existing file in Java
  4. How to write data with FileOutputStream without losing old data?