Hadoop的文件命令采取的形式为:hadoop fs -cmd <args>
其中cmd是具体的文件命令,而<args>是一组可变的参数。cmd的命名通常与Linux对应的命名相同。
1、添加文件和目录
创建目录:
hadoop fs -mkdir /user/root (Hadoop的mkdir命令会自动创建父目录,类似于Linux中的mkdir -p)
查看目录或文件信息:
hadoop fs -ls /user
hadoop fs -lsr / (lsr命令可以看到所有的子目录,类似于Linux中的ls -r)
上传本体文件到HDFS
hadoop fs -put /usr/example.txt /user/root/input
上图中文件权限后面的数字1表示所列给出的文件的复制因子(伪分布式下它永远为1),复制因子不适用于目录,所以目录前面给出的为-
2、检索文件
从HDFS取回文件
hadoop fs -get /user/root/input/example.txt /usr
访问HDFS中的文件
hadoop fs -cat /user/root/input/example.txt
Hadoop中的命令可以使用管道转给Linux中的命令,例如hadoop fs -cat /user/root/input/example.txt | head
Hadoop支持tail命令来查看文件的最后1000个字节
hadoop fs -tail /user/root/input/example.txt
3、删除文件
hadoop fs -rm
/user/root/input/example.txt
4、编程读写HDFS
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class uploadFile {
public static void main(String[] args) throws IOException{
Configuration conf = new Configuration();
FileSystem hdfs = FileSystem.get(conf);
FileSystem localFile = FileSystem.getLocal(conf);
Path localPath = new Path(args[0]); //设定输入文件和输出文件目录
Path hdfsPath = new Path(args[1]);
FSDataInputStream in = localFile.open(localPath);//得到本地文件生成输入流
FSDataOutputStream out = hdfs.create(hdfsPath);//生成HDFS输出流
int bytesRead = 0;
byte[] buffer = new byte[256];
while((bytesRead=in.read())!=0){
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
}
}