簡體   English   中英

使用 Scala 將文件寫入 Amazon S3 AWS 存儲

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

這是我的代碼的一部分:

   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()

我需要使用 Scala 將一個新文件寫入我的存儲桶中。 我收到此錯誤:

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

當我嘗試將其保存在本地時,它可以工作:

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

我怎么能解決呢? 提前致謝

S3A 作為 Hadoop 文件系統客戶端,您不能使用 java File API 來處理它。

  1. 創建一個包含所有 s3 憑據的 hadoop Configuration對象。 如果您使用的是 Spark,您可以從SparkContext免費獲得SparkContext
  2. 使用 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()

您現在可以使用 AWS Java SDK 直接編寫它。 這是示例;

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 是一個對象存儲,你不能寫字符串。 您可以將字符串寫入本地文件並定期將文件上傳到 S3。

暫無
暫無

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

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