We use HDFS read and write operations to store and access big data files across many computers easily and safely.
HDFS read and write operations in Hadoop
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; public class HDFSReadWrite { public static void main(String[] args) throws Exception { Configuration configuration = new Configuration(); FileSystem hdfs = FileSystem.get(configuration); // Write operation Path writePath = new Path("/user/hadoop/example.txt"); try (OutputStream outputStream = hdfs.create(writePath)) { String data = "Hello HDFS!"; outputStream.write(data.getBytes()); } // Read operation Path readPath = new Path("/user/hadoop/example.txt"); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(hdfs.open(readPath)))) { String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } } }
The FileSystem object connects to HDFS and lets you read or write files.
Use hdfs.create(path) to write a new file or overwrite an existing one.
// Writing to HDFS when file does not exist Path newFilePath = new Path("/user/hadoop/newfile.txt"); try (OutputStream outputStream = hdfs.create(newFilePath)) { outputStream.write("Data for new file".getBytes()); }
// Reading from HDFS when file exists Path existingFilePath = new Path("/user/hadoop/newfile.txt"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(hdfs.open(existingFilePath)))) { String line = reader.readLine(); System.out.println(line); }
// Reading from HDFS when file is empty Path emptyFilePath = new Path("/user/hadoop/emptyfile.txt"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(hdfs.open(emptyFilePath)))) { String line = reader.readLine(); System.out.println(line); // prints null }
// Writing to HDFS overwrites existing file Path overwritePath = new Path("/user/hadoop/newfile.txt"); try (OutputStream outputStream = hdfs.create(overwritePath)) { outputStream.write("Overwritten data".getBytes()); }
This program writes a text string to a file in HDFS and then reads it back to print on the screen.
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; public class HDFSReadWriteExample { public static void main(String[] args) throws Exception { Configuration configuration = new Configuration(); FileSystem hdfs = FileSystem.get(configuration); Path filePath = new Path("/user/hadoop/sample.txt"); System.out.println("Writing data to HDFS file..."); try (OutputStream outputStream = hdfs.create(filePath)) { String dataToWrite = "Welcome to HDFS read and write operations!"; outputStream.write(dataToWrite.getBytes()); } System.out.println("Reading data from HDFS file..."); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(hdfs.open(filePath)))) { String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } } }
Time complexity: Writing and reading depend on file size and network speed.
Space complexity: Uses memory for buffers during read/write.
Common mistake: Forgetting to close streams can cause data loss or errors.
Use write operation to save or overwrite files; use read operation to access stored data.
HDFS read and write let you store and access big data files across many machines.
Writing creates or overwrites files; reading fetches file contents line by line.
Always close streams to avoid errors and data loss.
Practice
write operation in HDFS primarily do?Solution
Step 1: Understand the purpose of write operation in HDFS
The write operation is used to create new files or overwrite existing files in HDFS.Step 2: Differentiate write from read and other operations
Reading fetches data, deleting removes files, listing shows files. Writing specifically saves data.Final Answer:
Creates or overwrites files in the distributed file system -> Option AQuick Check:
Write = Create or overwrite files [OK]
- Confusing write with read operation
- Thinking write deletes files
- Assuming write lists files
pyarrow library?Solution
Step 1: Identify the mode for reading files
In file operations, 'r' mode means open for reading, 'w' means writing.Step 2: Match the correct function call for reading
Using fs.open with 'r' opens the file for reading in pyarrow.Final Answer:
fs.open('/path/to/file', 'r') -> Option BQuick Check:
Open file with 'r' to read [OK]
- Using 'w' mode when reading
- Confusing open with read or write methods
- Forgetting to specify mode
pyarrow to read from HDFS:with fs.open('/data/sample.txt', 'r') as f:
lines = f.readlines()
print(len(lines))If the file contains 5 lines, what will be the output?
Solution
Step 1: Understand what readlines() returns
The readlines() method reads all lines and returns a list of lines.Step 2: Count the number of lines in the list
If the file has 5 lines, len(lines) will be 5.Final Answer:
5 -> Option AQuick Check:
readlines() returns list of lines, length = 5 [OK]
- Assuming readlines() returns a string
- Forgetting to close the file (but 'with' handles it)
- Confusing number of lines with characters
pyarrow?
f = fs.open('/data/output.txt', 'w')
f.write('Hello World')
# Missing f.close()Solution
Step 1: Check if file is properly closed after writing
The code opens file and writes but does not close it, which can cause data loss.Step 2: Understand importance of closing streams in HDFS
Closing the file ensures data is flushed and saved correctly in HDFS.Final Answer:
File is not closed, risking data loss -> Option DQuick Check:
Always close files after writing [OK]
- Ignoring file close after write
- Assuming write accepts only bytes (it accepts strings too)
- Confusing read and write modes
Solution
Step 1: Write data properly by opening and closing the file
Open the file in write mode, write the data, then close the file to save it safely.Step 2: Read data by opening file in read mode and closing after reading
After writing, open the file in read mode, read line by line, then close the file to release resources.Final Answer:
Open file in write mode, write data, close file; then open in read mode, read lines, close file -> Option CQuick Check:
Write then close; read then close [OK]
- Reading before writing data
- Not closing write stream before reading
- Trying to read or write without opening file
Ready to prove it?
Pass the test and this pattern moves unknown
