【问题标题】:How to read a spark saved file in java code如何在java代码中读取spark保存的文件
【发布时间】:2016-12-13 02:55:30
【问题描述】:

我是 Spark 的新手。我有一个文件 TrainDataSpark.java,我在其中处理一些数据,最后我将我的 spark 处理数据保存到一个名为 Predictions 的目录中,代码如下

predictions.saveAsTextFile("Predictions"); 

在同一个 TrainDataSpark.java 中,我在上面一行之后添加了下面的代码部分。

OutputGeneratorOptimized ouputGenerator = new OutputGeneratorOptimized();
final Path predictionFilePath = Paths.get("/Predictions/part-00000");
final Path outputHtml = Paths.get("/outputHtml.html");
ouputGenerator.getFormattedHtml(input,predictionFilePath,outputHtml);

我得到 /Predictions/part-00000 的 NoSuchFile 异常。我已经尝试了所有可能的路径,但都失败了。我认为 java 代码在我的本地系统而不是 hdfs 集群上搜索文件。有没有办法从集群中获取文件路径,以便我可以进一步传递它?或者有没有办法将我的预测文件加载到本地而不是集群,以便 java 部分运行时没有错误?

【问题讨论】:

  • Paths.get("/Predictions) 的结果是什么?
  • 只是路径 /user/username/Predictions/part-00000
  • 调用saveAsTextFile后,文件是否物理存在于/Predictions/part-00000下?
  • 是的.. 在调用 predictions.saveAsTextFile("Predictions"); Predictions 文件夹在 hdfs 上创建。里面是part-00000。我现在想阅读这个文件。

标签: apache-spark


【解决方案1】:

如果您在集群上运行 Spark,就会发生这种情况。 Paths.get 分别在每个节点的本地文件系统中查找文件,而它存在于 hdfs 上。您可能可以使用sc.textFile("hdfs:/Predictions")(或sc.textFile("Predictions"))加载文件。

另一方面,如果您想保存本地文件系统,则需要先collect RDD 并使用常规 Java IO 保存它。

【讨论】:

    【解决方案2】:

    我是这样想的……

    String predictionFilePath ="hdfs://pathToHDFS/user/username/Predictions/part-00000";
    String outputHtml = "hdfs://pathToHDFS/user/username/outputHtml.html";
    
    URI uriRead = URI.create(predictionFilePath);
    URI uriOut = URI.create(outputHtml);
    
    Configuration conf = new Configuration ();
    
    FileSystem fileRead = FileSystem.get (uriRead, conf);
    FileSystem fileWrite = FileSystem.get (uriOut, conf);
    
    FSDataInputStream in = fileRead.open(new org.apache.hadoop.fs.Path(uriRead));
    FSDataOutputStream out = fileWrite.append(new org.apache.hadoop.fs.Path(uriOut));
    
    /*Java code that uses stream objects to write and read*/
    OutputGeneratorOptimized ouputGenerator = new OutputGeneratorOptimized();
    ouputGenerator.getFormattedHtml(input,in,out);
    

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 2019-01-03
      • 1970-01-01
      • 2021-12-02
      • 2020-12-20
      • 1970-01-01
      相关资源
      最近更新 更多