简体   繁体   English

仅在while循环中调用函数时,才将文件发送到blob

[英]Sending file to blob only works when function is called in while loop

I have the Azure blob sample code which I'm trying to modify. 我有要修改的Azure blob示例代码。 However, the uploadFile function only works when it is in the while loop in a switch case. 但是,uploadFile函数仅在开关情况下处于while循环中时才起作用。 If I take it out of the loop, it creates the container but fails to upload the file. 如果我退出循环,它将创建容器,但无法上传文件。

I've tried taking it out and calling the function from different places in the code, but none of them work. 我尝试将其取出并从代码中的不同位置调用该函数,但是它们都不起作用。

uploadFile function: uploadFile函数:

 static void uploadFile(BlockBlobURL blob, File sourceFile) throws IOException {

        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(sourceFile.toPath());

        // Uploading a file to the blobURL using the high-level methods available in TransferManager class
        // Alternatively call the PutBlob/PutBlock low-level methods from BlockBlobURL type
        TransferManager.uploadFileToBlockBlob(fileChannel, blob, 8*1024*1024, null, null)
                .subscribe(response-> {
                    System.out.println("Completed upload request.");
                    TimeUnit.SECONDS.sleep(5);
                    System.out.println(response.response().statusCode());
                });


    }

Relevant part of main 主要相关部分

            // Listening for commands from the console
            //THIS IS THE PART THAT ONLY MAKES THE CONTAINER
            /*
            System.out.println("Uploading the sample file into the container: " + containerURL );
            uploadFile(blobURL, sampleFile);
            System.out.println("File Uploaded");
            */
            //TRYING TO CALL FUNCTION FROM OUTSIDE WHILE, BUT IT ONLY WORKS HERE
            System.out.println("Enter a command");
            System.out.println("(P)utBlob | (L)istBlobs | (G)etBlob");
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                System.out.println("# Enter a command : ");
                String input = reader.readLine();
                switch(input){
                    case "P":
                        System.out.println("Uploading the sample file into the container: " + containerURL );
                        uploadFile(blobURL, sampleFile);
                        break;

The uploadFile called outside of the while loop creates the container but doesn't actually upload a file to the blob, while uploadFile from in the while loop and switch case does 在while循环外部调用的uploadFile创建了容器,但实际上并未将文件上传到blob,而while循环和switch情况下的uploadFile确实可以

This won't upload the blob because the upload process has not finished and the main process has finished. 由于上传过程尚未完成且主过程已完成,因此不会上传Blob。 So I just add a Thread.sleep() to the main process. 因此,我只是将Thread.sleep()添加到主进程中。 And reminder don't set the value too short or it still fails. 并且提醒不要将值设置得太短,否则仍然会失败。 In my test I set it to 2000 millisecond. 在我的测试中,我将其设置为2000毫秒。

public static void main(String[] args) throws java.lang.Exception{


        ContainerURL containerURL;

        // Creating a sample file to use in the sample
        File sampleFile = null;

        try {
            sampleFile = File.createTempFile("downloadedFile", ".txt");

            // Retrieve the credentials and initialize SharedKeyCredentials
            String accountName = "xxxxxx";
            String accountKey = "xxxxxxx";

            // Create a ServiceURL to call the Blob service. We will also use this to construct the ContainerURL
            SharedKeyCredentials creds = new SharedKeyCredentials(accountName, accountKey);
            // We are using a default pipeline here, you can learn more about it at https://github.com/Azure/azure-storage-java/wiki/Azure-Storage-Java-V10-Overview
            final ServiceURL serviceURL = new ServiceURL(new URL("https://" + accountName + ".blob.core.windows.net"), StorageURL.createPipeline(creds, new PipelineOptions()));

            // Let's create a container using a blocking call to Azure Storage
            // If container exists, we'll catch and continue
            containerURL = serviceURL.createContainerURL("quickstart");

            try {
                ContainerCreateResponse response = containerURL.create(null, null, null).blockingGet();
                System.out.println("Container Create Response was " + response.statusCode());
            } catch (RestException e){
                if (e instanceof RestException && ((RestException)e).response().statusCode() != 409) {
                    throw e;
                } else {
                    System.out.println("quickstart container already exists, resuming...");
                }
            }

            // Create a BlockBlobURL to run operations on Blobs
            final BlockBlobURL blobURL = containerURL.createBlockBlobURL("SampleBlob.txt");

            System.out.println("Uploading the sample file into the container: " + containerURL );
            AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(sampleFile.toPath());


            // Uploading a file to the blobURL using the high-level methods available in TransferManager class
            // Alternatively call the PutBlob/PutBlock low-level methods from BlockBlobURL type
            TransferManager.uploadFileToBlockBlob(fileChannel, blobURL, 8*1024*1024, null, null)
                    .subscribe(response-> {
                        System.out.println("Completed upload request.");
                        System.out.println(response.response().statusCode());
                    });

            Thread.sleep(2000);

        } catch (InvalidKeyException e) {
            System.out.println("Invalid Storage account name/key provided");
        } catch (MalformedURLException e) {
            System.out.println("Invalid URI provided");
        } catch (RestException e){
            System.out.println("Service error returned: " + e.response().statusCode() );
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的 java 循环在我调用 function 时提前完成,但在未调用 function 时正常工作 - My java loop is finishing early when I call a function but works normally when the function is not called onFaceDetection在运行时只调用一次或两次,但在使用断点进行调试时效果很好 - onFaceDetection called only once or twice while running but works perfectly when debugging with breakpoints 按两次 ToggleButton 时无法在自定义线程中执行 while 循环(仅第一次有效) - Cannot perform a while loop in a custom Thread when pressing a ToggleButton twice (works only the first time) TextToSpeech仅在按下按钮时起作用,而不是在单独调用时起作用 - TextToSpeech only works when button is pressed, not when called separately JComponent,setEnabled()函数仅在首次调用时才能正常工作 - JComponent, setEnabled() function only works properly the first time it is called 通过套接字发送文件仅一次 - sending file over socket only works one time Java 套接字数据仅在发送时间延迟时才起作用 - Java socket data works only when sending time is delayed Swing java动画仅在未从侦听器调用时才起作用 - Swing java animation only works when not called from listener JNI包装的DLL仅在从默认包中调用时才有效 - JNI wrapped DLL only works when called from the default package Java函数仅适用于一个文本文件 - Java function only works with one text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM