簡體   English   中英

使用Java寫入文件並將文件上傳到Amazon S3時出現多個問題

[英]Multiple problems with writing to file and uploading file to Amazon S3 with Java

在嘗試將文本寫入文件然后將其上傳到AmazonS3存儲桶時,遇到了以下問題:

  • 文本被寫入文件,打開時我可以看到它
  • 文件已上傳到S3存儲桶,但dosObjectExist()方法返回false
  • 上傳的文件為空

下面是我的測試代碼:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

public class Main {

public static void main(String[] args) { 

    File test;
    File log;
    String [] messages = {"one", "two", "three"};
    PrintWriter testOut = null;
    PrintWriter logOut = null;

    test = new File(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "test.txt");
    log = new File(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "log.txt");

    try {
        testOut = new PrintWriter(new BufferedWriter(new FileWriter(test)));
        logOut = new PrintWriter(new BufferedWriter(new FileWriter(log)));
        for(int i = 0; i < messages.length; i++) {
            testOut.write(messages[i]);
            logOut.write("Writing message: " + messages[i] + " to test file.");
            testOut.write(System.lineSeparator());
            logOut.write(System.lineSeparator());
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();            
    } 

    BasicAWSCredentials credentials = new BasicAWSCredentials("ACCESS_KEY_ID", "SECRET_ACCESS_KEY");
    AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withRegion("eu-west-1").build();
    try {
        s3Client.putObject("test", "test/test.txt", test);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }


    logOut.write("Uploading test.txt to test");
    logOut.write(System.lineSeparator());
    boolean b1 = s3Client.doesObjectExist("test", "test.txt");
    logOut.write("File test.txt uploaded to test: " + b1);
    logOut.write(System.lineSeparator());

    testOut.flush();
    testOut.close();
    logOut.write("Closing testOut PrintWriter");
    logOut.write(System.lineSeparator());
    logOut.flush();
    logOut.close();
}
}

有人可以幫忙嗎?

上傳后,您似乎正在刷新並關閉testOut。 您應該在上傳之前移動這2條命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM