2015-12-30 122 views
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异常)

回答

1

我可以看到3种可能性:

  1. 最容易的方法是使用由您的Hadoop集群上的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
  2. 如果你不想使用HDFS commnads,那么你可能会使用由hadoop-hdfshttp://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs/2.7.1
  3. 使用星火,如果你想干净斯卡拉的解决方案,例如提供HDFS API http://spark.apache.org/docs/latest/programming-guide.htmlhttps://databricks.gitbooks.io/databricks-spark-reference-applications/content/logs_analyzer/chapter3/save_the_rdd_to_files.html
相关问题