0
我想將文本文件寫入HDFS。 文件必須寫入HDFS的路徑是動態生成的。 如果文件路徑(包括文件名)是新的,則該文件應創建和文字應被寫入。 如果文件路徑(包括文件)已經存在,則字符串必須附加到現有文件。如何使用Scala使用Hadoop客戶端在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異常)