简体   繁体   English

使用 Scala 将文件写入 Amazon S3 AWS 存储

[英]Writing a file into Amazon S3 AWS Storage using Scala

this is part of my code:这是我的代码的一部分:

   val file=new File("s3a://tracce/output/Tempi.txt") 
   val writer=new BufferedWriter(new FileWriter(file,true))
   writer.write("Execution Time trace "+count.toString+"x"+i.toString+": "+differenza.toString)
   writer.newLine()
   writer.flush()
   writer.close()

I need to write a new file into my bucket using Scala.我需要使用 Scala 将一个新文件写入我的存储桶中。 I get this error:我收到此错误:

Exception in thread "main" java.io.FileNotFoundException:     s3:/tracce/output/Tempi.txt (No such file or directory)

When I try to save it locally, it works:当我尝试将其保存在本地时,它可以工作:

val file=new File("./Tempi.txt")

How could I solve it?我怎么能解决呢? Thanks in advance提前致谢

S3A being a Hadoop Filesystem client, you can't use the java File API to work with it. S3A 作为 Hadoop 文件系统客户端,您不能使用 java File API 来处理它。

  1. Create a hadoop Configuration object with all your s3 credentials in them.创建一个包含所有 s3 凭据的 hadoop Configuration对象。 If you are using Spark, you get that for free from SparkContext .如果您使用的是 Spark,您可以从SparkContext免费获得SparkContext
  2. Use the Hadoop FS API to get the FS instance, create() to create a file in it.使用 Hadoop FS API 获取 FS 实例, create()在其中创建文件。
import org.apache.hadoop.fs._
    import org.apache.hadoop.conf.Configuration
    val conf = new Configuration()
    conf.set("fs.s3a.access.key", "YOUR ACCESS KEY")
    conf.set("fs.s3a.secret.key", "YOUR SECRET KEY")

    val dest = new Path("s3a://bucket_name/output-path/file.txt")
    val fs = dest.getFileSystem(conf)
    val out = fs.create(dest, true)
    out.write( /* your string as bytes */ )
    out.close()

You can now write it directly using the AWS Java SDK.您现在可以使用 AWS Java SDK 直接编写它。 Here is the example;这是示例;

import com.amazonaws.services.s3.{AmazonS3, AmazonS3ClientBuilder}

val s3Client: AmazonS3 = AmazonS3ClientBuilder.defaultClient()

val bucketName = "bucket-name"
val objectKey = "object-key"
val objectContent = "This is the file content."

s3Client.putObject(bucketName, objectKey, objectContent)

S3 being an object store, you cannot write strings. S3 是一个对象存储,你不能写字符串。 You can probably write the strings to a local file and periodically upload the file to S3.您可以将字符串写入本地文件并定期将文件上传到 S3。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM