繁体   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