Reputation: 15599
In a java app running on an edge node, I need to delete a hdfs folder, if it exists. I need to do that before running a mapreduce job (with spark) that output in the folder.
I found I could use the method
org.apache.hadoop.fs.FileUtil.fullyDelete(new File(url))
However, I can only make it work with local folder (i.e. file url on the running computer). I tried to use something like:
url = "hdfs://hdfshost:port/the/folder/to/delete";
with hdfs://hdfshost:port
being the hdfs namenode IPC. I use it for the mapreduce, so it is correct.
However it doesn't do anything.
So, what url should I use, or is there another method?
Note: here is the simple project in question.
Upvotes: 10
Views: 28992
Reputation: 351
if you need to delete all files in the directory:
1) check how many files are there in your directory.
2) later delete all of them
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();
}
}
}
good luck :)
Upvotes: 0
Reputation: 381
This works for me.
Just add the following codes in my WordCount program will do:
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");
...
You need to add hdfs://hdfshost:port
explicitly to get distributed file system. Else the code will work for local file system only.
Upvotes: 21
Reputation: 7362
I do it this way:
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);
you don't need hdfs://hdfshost:port/
in your file path
Upvotes: 13