1. Criar projeto e maven de importação pacote jar
jdk uso 1.8, versão maven3.x
Adicionar cerca de pom.xml conteúdo
<repositórios> <repositório> <id> Cloudera </ id> <url> https://repository.cloudera.com/artifactory/cloudera-repos/ </ url> </ repositório> </ repositórios> <dependencies> <dependency > <groupId> org.apache.hadoop </ groupId> <artifactId> hadoop-cliente </ artifactId> <versão> 2.6.0-MR1-cdh5.14.2 </ version> </ dependency> <dependency> <groupId> org .apache.hadoop </ groupId> <artifactId> hadoop-comum </ artifactId> <versão> 2.6.0-cdh5.14.2 </ version> </ dependency> <dependency> <groupId> org.apache.hadoop </ groupId> <artifactId> hadoop-hdfs </ artifactId> <versão> 2.6.0-cdh5.14.2 </ version> </ dependency> <dependency> <groupId> org.apache.hadoop </ groupId> <artifactId> hadoop-mapreduce- cliente-core </ artifactId> <versão> 2.6.0-cdh5.14.2 </ version> </ dependency> <! - https://mvnrepository.com/artifact/junit/junit -> <dependency> <groupId > junit </ groupId> <artifactId> junit </ artifactId> <versão> 4,11 </ version> <scope> test </ scope> </ dependency> <dependency> <groupId> org.testng </ groupId> <artifactId> testng </ artifactId> <version> Datas </ version> </ dependency> </ dependencies> <build> <plugins> <plug-in> <groupId> org.apache.maven.plugins </ groupId> <artifactId> maven-compiler-plugin </ artifactId > <version> 3.0 </ version> <configuration> <source> 1,8 </ source> <meta> 1,8 </ target> <encoding> UTF-8 </ encoding> <! - <verbal> true </ verbal> -> </ configuration> </ plugin> <plug-in> <groupId> org.apache.maven.plugins </ groupId> <artifactId> maven-sombra-plugin </ artifactId> <versão> 2.4.3 </ Version> <execuções> <execução> <fase> pacote </ fase> <metas> <meta> sombra </ Meta> </ metas > <configuration> <minimizeJar> true </ minimizeJar> </ configuration> </ execução> </ execuções> </ plugin> </ plugins> </ build>
Criando com.my.hdfs sob o diretório 2.Test e criar arquivos no HDFSOperate.java pacote
2.1 Criar uma pasta
@Test mkdirToHdfs public void () throws IOException {
configuração = new Configuration (); configuration.set ( "fs.defaultFS", "HDFS: // node01: 8020"); FileSystem fileSystem = FileSystem.get (configuração); fileSystem.mkdirs (novo caminho ( "/ dir1")); // hdfs路径 fileSystem.close (); }
Upload 2.2 arquivo
@Test uploadFile public void () throws IOException { Configuração de configuração = new Configuration (); configuration.set ( "fs.defaultFS", "HDFS: // node01: 8020"); FileSystem fileSystem = FileSystem.get (configuração); fileSystem.copyFromLocalFile (novo caminho ( "file: /// d: \\ hello.txt") / **本地目录* /, novo Path ( "hdfs: // node01: 8020 / dir1") / ** hdfs目录* /); fileSystem.close (); }
2.3 Baixar
@Test
DownloadFile public void () throws IOException { Configuração de configuração = new Configuration (); configuration.set ( "fs.defaultFS", "HDFS: // node01: 8020"); FileSystem fileSystem = FileSystem.get (configuração); fileSystem.copyToLocalFile (novo caminho ( "hdfs: // node01: 8020 / dir1 / hello.txt") / ** hdfs目录* /, novo Path ( "file: /// d: \\ hello2.txt") / **本地目录* /); fileSystem.close (); }
2.4 exclusão de arquivos
@Test deleteHDFS public void () throws IOException { Configuração conf = new Configuration (); conf.set ( "fs.defaultFS", "HDFS: // node01: 8020"); FileSystem fs = FileSystem.get (conf); fs.delete (novo caminho ( "/ dir1 / hello.txt"), true); fs.close (); }
2,5 Renomeamento
@Test renameDFS public void () throws IOException { Configuração conf = new Configuration (); conf.set ( "fs.defaultFS", "HDFS: // node01: 8020"); FileSystem fs = FileSystem.get (conf); fs.rename (novo caminho ( "/ dir1 / hello.txt"), novo caminho ( "/ dir1 / hello.md")); fs.close (); }
2,6 hdfs visualizar informações de arquivos
@Test testListFiles public void () throws IOException, InterruptedException, um URISyntaxException para { // Obter sistema de arquivos 1. Configuração Configuração nova new = Configuração (); o sistema de arquivos FileSystem.get FS = (nova novo o URI ( "HDFS: // amdha01: 8020"), de configuração ); // Obter Detalhe arquivo 2 RemoteIterator <LocatedFileStatus> = fs.listFiles os ListFiles (nova novo o caminho ( "/"), a verdade); o tempo (listFiles.hasNext ()) { LocatedFileStatus listFiles.next status = (); // output detalhes // nome do arquivo System.out.println (status.getPath () getName ().); // comprimento System.out.println (status.getLen ()); // permissões System.out.printlnl (status.getPermission ()); // pacote System.out.printlnl (status.getGroup ()); // armazenado bloco de aquisição de informação BlockLocation [] = blockLocations status.getBlockLocations (); para (BlockLocation blockLocation: blockLocations) { // host bloco de aquisição nó armazenado string [] = blockLocation.getHosts os anfitriões (); para (string host: os anfitriões) { System.out.println (host); } } } . // perto o recurso 3 fs .close (); }
3.java API através IO córregos operando hdfs arquivo
3.1 io upload de dados de fluxo
@Test putFileToHDFS public void () throws IOException, InterruptedException, um URISyntaxException para { // Obter sistema de arquivos 1. Configuração Configuração nova new = Configuração (); o sistema de arquivos FileSystem.get FS = (nova novo o URI ( "HDFS: // amdha01: 8020"), de configuração ); // Cria fluxo de entrada não requer adicional de 2 file: /// o FileInputStream novo novo FIS = FileInputStream (new new File ( "E: \\ helo.txt")); . // obter um fluxo de saída 3 FSDataOutputStream fos = fs.create ( Caminho novos novos ( "HDFS: // amdha01: 8020 / outresult.txt")); // fluir 4 Duikao. IOUtils.copy (FIS, fos); // Fechar o recurso 5. IOUtils.closeQuietly (FOS); IOUtils.closeQuietly ( FIS); fs.Close (); }
3.2 io download de dados de fluxo
@Test getFileFromHDFS public void () throws IOException { Configuração conf = new Configuration (); conf.set ( "fs.defaultFS", "hdfs: / [表情] DE01: 8020"); FileSystem fs = FileSystem.get (conf); FSDataInputStream fis = fs.open (novo caminho ( "/ dir1 / hello.txt")); FileOutputStream fos = FileOutputStream novo ( "D: /hello_2.txt"); // sistema de arquivos关闭 IOUtils.copy (FIS, fos); IOUtils.closeQuietly (FIS); IOUtils.closeQuietly (FOS); fs.close (); }
3.3 hdfs pequenos arquivos de mesclagem
/ ** * pequeno arquivo de mesclagem * / @Test MergeFile public void () lança URISyntaxException, IOException, InterruptedException { // obter sistema de arquivos distribuídos HDFS o sistema de arquivos = FileSystem.get o sistema de arquivos (URI dos novos novos ( "HDFS: // node01: 8020" ), a configuração de novos novos (), "Hadoop"); fSDataOutputStream fsDataOutputStream = fileSystem.create (nova novo caminho ( "HDFS: // node01: 8020 / bigfile.xml")); // obter sistema de arquivos local LocalFileSystem LocalFileSystem LocalFileSystem = o sistema de arquivos. o getLocal (Configuração nova new ()); // lê o arquivo local fileStatus a [] = fileStatuses localFileSystem.listStatus (nova novo o caminho ( "file: /// D: smallFiles")); para (fileStatus um filestatus: fileStatuses) {
// aquisição de cada caminho de arquivo local o caminho caminho = fileStatus.getPath (); // lê o pequeno arquivo local FSDataInputStream fsDataInputStream = localFileSystem.open (caminho); IOUtils.copy (fsDataInputStream, fsDataOutputStream); IOUtils.closeQuietly (fsDataInputStream); } IOUtils.closeQuietly (fsDataOutputStream); localFileSystem.close (); fileSystem.close (); // ler todos os arquivos pequenos locais, grande arquivo é gravado para ir para dentro hdfs }