javacsvazurestoragecsv-write-stream

Generate CSV from Java object and move to Azure Storage without intermediate location


Is it possible to create a file like CSV from Java object and move them to Azure Storage without using temporary location?


Solution

  • According to your description , it seems that you want to upload a CSV file without taking up your local space. So, I suggest you use stream to upload CSV files to Azure File Storage.

    Please refer to the sample code as below :

    import com.microsoft.azure.storage.CloudStorageAccount;
    import com.microsoft.azure.storage.file.CloudFile;
    import com.microsoft.azure.storage.file.CloudFileClient;
    import com.microsoft.azure.storage.file.CloudFileDirectory;
    import com.microsoft.azure.storage.file.CloudFileShare;
    import com.microsoft.azure.storage.StorageCredentials;
    import com.microsoft.azure.storage.StorageCredentialsAccountAndKey;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.StringBufferInputStream;
    
    public class UploadCSV {
    
        // Configure the connection-string with your values
        public static final String storageConnectionString =
                "DefaultEndpointsProtocol=http;" +
                        "AccountName=<storage account name>;" +
                        "AccountKey=<storage key>";
    
    
        public static void main(String[] args) {
            try {
                CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
    
                // Create the Azure Files client.
                CloudFileClient fileClient = storageAccount.createCloudFileClient();
    
                StorageCredentials sc = fileClient.getCredentials();
    
                // Get a reference to the file share
                CloudFileShare share = fileClient.getShareReference("test");
    
                //Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
    
                //Get a reference to the file you want to download
                CloudFile file = rootDir.getFileReference("test.csv");
    
                file.upload( new StringBufferInputStream("aaa"),"aaa".length());
    
                System.out.println("upload success");
    
            } catch (Exception e) {
                // Output the stack trace.
                e.printStackTrace();
            }
        }
    }
    

    Then I upload the file into the account successfully.

    enter image description here

    You could also refer to the threads:

    1.Can I upload a stream to Azure blob storage without specifying its length upfront?

    2.Upload blob in Azure using BlobOutputStream

    Hope it helps you.