2016-05-17 86 views
0

問題覆寫HDFS文件/目錄

我保存在HDFS文件和所有我想要做的就是運行我的火花的應用程序,計算結果javaRDD,爲了存儲新的使用saveAsTextFile() HDFS中的「文件」。

但是,如果文件已存在,Spark的saveAsTextFile()不起作用。它不覆蓋它。

我試過

所以我尋找一個解決方案,這一點,我發現一個可行的辦法,使其試圖保存新的一個工作之前可以通過HDFS API來刪除文件。

我添加的代碼:

FileSystem hdfs = FileSystem.get(new Configuration()); 
Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename); 

if(hdfs.exists(newFolderPath)){ 
    System.out.println("EXISTS"); 
    hdfs.delete(newFolderPath, true); 
} 

filerdd.saveAsTextFile("/hdfs/" + filename); 

當我試圖運行我的星火應用程序,該文件已被刪除,但我得到一個FileNotFoundException

考慮到這樣的事實,即當有人試圖從路徑中讀取文件並且文件不存在時發生此異常,這是沒有意義的,因爲在刪除文件之後,沒有代碼嘗試讀取它。我的代碼

JavaRDD<String> filerdd = sc.textFile("/hdfs/" + filename) // load the file here 
... 
... 
// Transformations here 
filerdd = filerdd.map(....); 
... 
... 

// Delete old file here 
FileSystem hdfs = FileSystem.get(new Configuration()); 
Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename); 

if(hdfs.exists(newFolderPath)){ 
    System.out.println("EXISTS"); 
    hdfs.delete(newFolderPath, true); 
} 

// Write new file here 
filerdd.saveAsTextFile("/hdfs/" + filename); 

部分,我想在這裏做最簡單的事情,但我不知道爲什麼這是行不通的。也許filerdd以某種方式連接到路徑?

+0

你可以添加堆棧跟蹤嗎? – javadba

回答

1

問題是您使用相同的路徑進行輸入和輸出。 Spark的RDD將被延遲執行。它在您撥打saveAsTextFile時運行。此時,您已經刪除了newFolderPath。所以filerdd會抱怨。

無論如何,你不應該使用相同的路徑輸入和輸出。

+0

但是將文件保存在HDFS中的另一個路徑中對我來說不起作用,因爲我多次執行了我的Spark應用程序,並且始終希望使用保存爲輸入的最新文件。 – pirox22

+0

只需將文件保存在臨時路徑中即可。運行'saveAsTextFile'後,您可以刪除輸入並使用輸入路徑重命名臨時路徑。 – zsxwing