JAvaコードによるhdfsファイルの基本操作
19424 ワード
クラスタを配備していない仮想マシンがクラスタ上のhadoopにアクセスしたい場合:hadoopをインストールしcore-site.xmlを構成してfs.defaultFSパラメータをhdfs://master:9000対応するhadoopコマンドを直接実行すればよい(実行可能ファイル)ブロックサイズとバックアップこれらのパラメータは、どのマシンに置かれているかに関係なく、クライアントの関連構成に依存します.
package hdfs04;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
public class HdfsClientDemo {
public static void main(String[] args) throws Exception {
//new Configuration() classpath core-default.xml hdfs-default.xml core-site.xml hdfs-site.xml
/*
Configuration :
, jar xx-default.xml
xx-site.xml
, conf.set("",""),
*/
Configuration conf=new Configuration();
// hdfs :2
conf.set("dfs.replication","2");
// hdfs
conf.set("dfs.blocksize","64M");
// HDFS
// 1:HDFS URI 2: 3: ( )
FileSystem fs=FileSystem.get(new URI("hdfs://master:9000/"),conf,"root");
// HDFS
fs.copyFromLocalFile(new Path("D:/menu.txt"),new Path("/"));
fs.close();
}
FileSystem fs=null;
@Before
public void init() throws Exception{
Configuration conf=new Configuration();
conf.set("dfs.replication","2");
fs=FileSystem.get(new URI("hdfs://master:9000"),conf,"root");
}
@Test //
public void testGet() throws Exception {
// hadoop c lib HADOOP_HOME windows hadoop
fs.copyToLocalFile(new Path("/menu.txt"),new Path("e:/"));
fs.close();
}
@Test // hdfs /
public void testRename() throws Exception{
//
fs.rename(new Path("/menu.txt"),new Path("/aaa/m.txt"));
fs.close();
}
@Test
// hdfs
public void testMkdirs() throws Exception{
fs.mkdirs(new Path("/xx/yy"));
fs.close();
}
@Test
// hdfs
public void TestRm() throws Exception{
fs.delete(new Path("/xx"),true);
fs.close();
}
@Test
// hdfs ( )
public void testLs() throws Exception{
//
RemoteIterator<LocatedFileStatus> iter = fs.listFiles(new Path("/"), true);
while(iter.hasNext()){
LocatedFileStatus status=iter.next();
System.out.println(" : "+status.getLen());
// namende 。( )
System.out.println(" : "+Arrays.toString(status.getBlockLocations()));
fs.close();
}
}
@Test
// hdfs
public void testLs2() throws Exception {
FileStatus[] liststatus=fs.listStatus(new Path("/"));//
for(FileStatus status: liststatus){
System.out.println(" "+status.getPath());
System.out.println(status.isDirectory()?" ":" ");
System.out.println(status.getReplication());
System.out.println("");
}
}
}