Common Operations and precautions for hadoop HDFS files

Source: Internet
Author: User

1. copy a file from the local file system to HDFS

The srcfile variable needs to contain the full name (path + file name) of the file in the local file system.

The dstfile variable needs to contain the desired full name of the file in the hadoop file system.

1 Configuration config = new Configuration();2 FileSystem hdfs = FileSystem.get(config);3 Path srcPath = new Path(srcFile);4 Path dstPath = new Path(dstFile);5 hdfs.copyFromLocalFile(srcPath, dstPath);

2. Create HDFS File

The filename variable contains the file name and path in the hadoop file system.

The content of the file is the buff variable which is an array of bytes.

1 // byte [] buff-the content of the file 2 // creates an HDFS file and writes the content of the buff array to the HDFS file. 3 configuration Config = new configuration (); 4 filesystem HDFS = filesystem. get (config); 5 Path = New Path (filename); 6 fsdataoutputstream outputstream = HDFS. create (PATH); 7 outputstream. write (buff, 0, Buff. length );

3. Rename HDFS File

In order to rename a file in hadoop file system, we need the full name (path + name)

The file we want to rename. The rename method returns true if the file was renamed, otherwise false.

1   Configuration config = new Configuration();2   FileSystem hdfs = FileSystem.get(config);3   Path fromPath = new Path(fromFileName);4   Path toPath = new Path(toFileName);5   boolean isRenamed = hdfs.rename(fromPath, toPath);

4. Delete HDFS File

In order to delete a file in hadoop file system, we need the full name (path + name)

Of the file we want to delete. The delete method returns true if the file was deleted, otherwise false.

1 configuration Config = new configuration (); 2 filesystem HDFS = filesystem. get (config); 3 Path = New Path (filename); 4 Boolean isdeleted = HDFS. delete (path, false); 5 6 // recursive Delete: it is estimated that true is used recursively to delete files under this directory. 7 configuration Config = new configuration (); 8 filesystem HDFS = filesystem. get (config); 9 Path = New Path (filename); 10 Boolean isdeleted = HDFS. delete (path, true );

5. Get HDFS file last modification time

In order to get the last modification time of a file in hadoop file system,

We need the full name (path + name) of the file.

1   Configuration config = new Configuration();2   FileSystem hdfs = FileSystem.get(config);3   Path path = new Path(fileName);4   FileStatus fileStatus = hdfs.getFileStatus(path);5   long modificationTime = fileStatus.getModificationTime

6. Check if a file exists in HDFS

In order to check the existance of a file in hadoop file system,

We need the full name (path + name) of the file we want to check.

The exists Methods returns true if the file exists, otherwise false.

1 Configuration config = new Configuration();2 FileSystem hdfs = FileSystem.get(config);3 Path path = new Path(fileName);4 boolean isExists = hdfs.exists(path);

7. Get the locations of a file in the HDFS Cluster

A file can exist on more than one node in the hadoop file system cluster for two reasons:

Based on the HDFS cluster configuration, hadoop saves parts of files on different nodes in the cluster.

Based on the HDFS cluster configuration, hadoop saves more than one copy of each file on different nodes for redundancy (the default is three ).

 1 Configuration config = new Configuration(); 2 FileSystem hdfs = FileSystem.get(config); 3 Path path = new Path(fileName); 4 FileStatus fileStatus = hdfs.getFileStatus(path); 5 BlockLocation[] blkLocations = hdfs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen()); 6 int blkCount = blkLocations.length; 7 for (int i = 0; i < blkCount; i++) { 8     String[] hosts = blkLocations[i].getHosts(); 9     // Do something with the block hosts10 }

8. Get a list of all the nodes host names in the HDFS Cluster

His method casts the filesystem object to a distributedfilesystem object.

This method will work only when hadoop is configured as a cluster.

Running hadoop on the local machine only, in a non cluster configuration will cause this method to throw an exception.

1   Configuration config = new Configuration();2   FileSystem fs = FileSystem.get(config);3   DistributedFileSystem hdfs = (DistributedFileSystem) fs;4   DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();5   String[] names = new String[dataNodeStats.length];6   for (int i = 0; i < dataNodeStats.length; i++) {7       names[i] = dataNodeStats[i].getHostName();8   }

 

Problems encountered and solutions:

1. File append Problems

After hadoop version 1.0.4, the API already has the append write function, but it is not recommended to use it in the production environment. The reason is as follows: does HDFS allow appends to files? This is currently set to false because there are bugs in the "APPEND code" and is not supported in any prodction cluster.
If you want to test the function, set the DFS. Support. appen parameter to true. Otherwise, an error is returned when the client writes data:

Exception in thread "main" org.apache.hadoop.ipc.RemoteException: java.io.IOException: Append to hdfs not supported. Please refer to dfs.support.append configuration parameter.

Solution: Modify the hdfs-site.xml on the namenode node.

  <property>    <name>dfs.support.append</name>    <value>true</value>  </property>

2. When using append for Hadoop-1.0.4 and Hadoop-2.2, requirement: append Write File, if file does not exist, need to be created first.

Exception:

Exception in thread "main" org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException: failed to create file /huangq/dailyRolling/mommy-dailyRolling for DFSClient_-1456545217 on client 10.1.85.243 because current leaseholder is trying to recreate file.    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.recoverLeaseInternal(FSNamesystem.java:1374)    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInternal(FSNamesystem.java:1246)    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.appendFile(FSNamesystem.java:1426)    at org.apache.hadoop.hdfs.server.namenode.NameNode.append(NameNode.java:643)    at sun.reflect.GeneratedMethodAccessor25.invoke(Unknown Source)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)    at java.lang.reflect.Method.invoke(Method.java:597)

Code version 1: (The above error code is reported)

1 FileSystem fs = FileSystem.get(conf);2 Path dstPath = new Path(dst);3 if (!fs.exists(dstPath)) {4     fs.create(dstPath);5 } 6 FSDataOutputStream fsout = fs.append(dstPath);7 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fsout));

Cause of exception: the cause of the FS handle is changed to the following: OK.

Solution: after creating the file, close the stream FS and get a new FS again.

1 FileSystem fs = FileSystem.get(conf);2 Path dstPath = new Path(dst);3 if (!fs.exists(dstPath)) {4     fs.create(dstPath);5     fs.close();6     fs = FileSystem.get(conf);7 } 8 FSDataOutputStream fsout = fs.append(dstPath);

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.