Path path = new Path("folder");
FileStatus fss = fs.getFileStatus(path);
Creating File in HDFS
Writing data to hdfs file
/**
* Writing data to hdfs file
* @param content raw data
* @param dstPath Destination file in HDFS
* @throws IOException
*/
public void writingData2HdfsFile(String content, String dstPath) throws IOException {
// Get configuration of Hadoop system
Configuration conf = new Configuration();
try (
FileSystem fs = FileSystem.get(conf);
FSDataOutputStream fsos = fs.create(new Path(dstPath))
) {
byte[] buffer = content.getBytes();
fsos.write(buffer, 0, buffer.length);
}
}
Writing a file to Hdfs file
/**
* Writing a file to Hdfs
* @param localSrc Source file in the local file system
* @param hdfsDst Destination file in HDFS
* @throws IOException
*/
public void srcFile2HdfsFile(String localSrc, String hdfsDst) throws IOException {
// Input stream for the file in local file system to be written to HDFS
InputStream in = new BufferedInputStream(new FileInputStream(localSrc));
// Get configuration of Hadoop system
Configuration conf = new Configuration();
System.out.println("Connecting to -- " + conf.get("fs.defaultFS"));
// Destination file in HDFS
FileSystem fs = FileSystem.get(URI.create(hdfsDst), conf);
OutputStream out = fs.create(new Path(hdfsDst));
//Copy file from local to HDFS
IOUtils.copyBytes(in, out, 4096, true);
System.out.println(hdfsDst + " copied to HDFS");
}
Writing a Source hdfs File to Destination hdfs file
/**
*
* @param srcPath Source file in HDFS
* @param dstPath Destination file in HDFS
* @throws IOException
*/
public void srcHdfsFile2DstHdfsFile(String srcPath, String dstPath) throws IOException {
Configuration conf = new Configuration();
try (
FileSystem fs = FileSystem.get(conf);
// Source file in HDFS
FSDataInputStream fis = fs.open(new Path(srcPath));
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
// Destination file in HDFS
FSDataOutputStream fos = fs.create(new Path(dstPath));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, Charset.forName("GBK")))
) {
String line;
while ((line = br.readLine()) != null) {
bw.append(line).append(System.getProperty("line.separator"));
}
}
}
Configuration
import
FileSystem
import
Get FileSystem
Get home directory
Get Working directory
Create a blank file in hdfs
Result:
FileStatus
import
Creating File in HDFS
Writing data to hdfs file
Writing a file to Hdfs file
Writing a Source hdfs File to Destination hdfs file
References