[英]How to append text files in HDFS using Hadoop client using Scala?
我想將文本文件寫入HDFS。 動態生成必須將文件寫入HDFS的路徑。 如果文件路徑(包括文件名)是新的,則應創建文件並向其中寫入文本。 如果文件路徑(包括文件)已經存在,則必須將字符串附加到現有文件之后。
我用下面的代碼。 文件創建工作正常。 但是不能將文本追加到現有文件中。
def writeJson(uri: String, Json: JValue, time: Time): Unit = {
val path = new Path(generateFilePath(Json, time))
val conf = new Configuration()
conf.set("fs.defaultFS", uri)
conf.set("dfs.replication", "1")
conf.set("dfs.support.append", "true")
conf.set("dfs.client.block.write.replace-datanode-on-failure.enable","false")
val Message = compact(render(Json))+"\n"
try{
val fileSystem = FileSystem.get(conf)
if(fileSystem.exists(path).equals(true)){
println("File exists.")
val outputStream = fileSystem.append(path)
val bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream))
bufferedWriter.write(Message.toString)
bufferedWriter.close()
println("Appended to file in path : " + path)
}
else {
println("File does not exist.")
val outputStream = fileSystem.create(path, true)
val bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream))
bufferedWriter.write(Message.toString)
bufferedWriter.close()
println("Created file in path : " + path)
}
}catch{
case e:Exception=>
e.printStackTrace()
}
}
Hadoop版本:2.7.0
每當必須執行附加操作時,就會產生以下錯誤:
org.apache.hadoop.ipc.RemoteException(java.lang.ArrayIndexOutOfBoundsException)
我可以看到3種可能性:
hdfs
提供的外部命令,請參閱: https : //hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HDFSCommands.html 。 甚至WebHDFS REST功能: https ://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/WebHDFS.html hadoop-hdfs
庫http://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs/2.7.1提供的hdfs API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.