![](/img/trans.png)
[英]How to copy a file from one HDFS folder to another HDFS folder using Java API?
[英]Delete hdfs folder from java
在邊緣節點上運行的Java應用程序中,我需要刪除hdfs文件夾(如果存在)。 我需要在運行在文件夾中輸出的mapreduce作業(帶有spark)之前執行此操作。
我發現我可以使用這種方法
org.apache.hadoop.fs.FileUtil.fullyDelete(new File(url))
但是,我只能使用本地文件夾(即正在運行的計算機上的文件URL)。 我嘗試使用類似的東西:
url = "hdfs://hdfshost:port/the/folder/to/delete";
使用hdfs://hdfshost:port
是hdfs namenode IPC。 我用它來mapreduce,所以它是正確的。 但它沒有做任何事情。
那么,我應該使用什么網址,還是有其他方法?
注意: 這是一個簡單的項目。
這適合我。
只需在我的WordCount程序中添加以下代碼即可:
import org.apache.hadoop.fs.*;
...
Configuration conf = new Configuration();
Path output = new Path("/the/folder/to/delete");
FileSystem hdfs = FileSystem.get(URI.create("hdfs://namenode:port"),conf);
// delete existing directory
if (hdfs.exists(output)) {
hdfs.delete(output, true);
}
Job job = Job.getInstance(conf, "word count");
...
您需要顯式添加hdfs://hdfshost:port
以獲取分布式文件系統。 否則,代碼僅適用於本地文件系統。
我是這樣做的:
Configuration conf = new Configuration();
conf.set("fs.hdfs.impl",org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
conf.set("fs.file.impl",org.apache.hadoop.fs.LocalFileSystem.class.getName());
FileSystem hdfs = FileSystem.get(URI.create("hdfs://<namenode-hostname>:<port>"), conf);
hdfs.delete("/path/to/your/file", isRecursive);
你的文件路徑中不需要hdfs://hdfshost:port/
如果您需要刪除目錄中的所有文件:
1)檢查目錄中有多少文件。
2)稍后刪除所有這些
public void delete_archivos_dedirectorio() throws IOException {
//namenode= hdfs://ip + ":" + puerto
Path directorio = new Path(namenode + "//test//"); //nos situamos en la ruta//
FileStatus[] fileStatus = hdfsFileSystem.listStatus(directorio); //listamos los archivos que hay actualmente en ese directorio antes de hacer nada
int archivos_basura = fileStatus.length; //vemos cuandoarchivos hay en el directorio antes de hacer nada, y luego iteramos hasta el nuemro de archivos que haya y llos vamos borrando para luego ir crandolos de nuevo en el writte.
for (int numero = 0; numero <= archivos_basura ; numero++) {
Path archivo = new Path(namenode + "//test//" + numero + ".txt");
try {
if(hdfsFileSystem.exists(archivo)) {
try {
hdfsFileSystem.delete(archivo, true);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
祝好運 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.