Creating basic file readers
You're working as a data analyst at a startup that tracks industry trends. Your team receives CSV files daily with market data that needs to be processed. As the first step in building a data pipeline, you need to create a reliable way to read these files and verify their existence before processing.
The File, Path, Paths, and Files classes have been imported for you.
This exercise is part of the course
Importing Data in Java
Exercise instructions
- Create a
Fileobject using the file path. - Check if the file exists.
- Get the file size in bytes.
- Create a
Pathobject from the file path.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class BasicFileReaders {
public static void main(String[] args) {
String filePath = "sample_market_data.csv";
// Create a File object
File file = new File(____);
// Check if the file exists
System.out.println("File exists: " + ____.____());
// Get the file size in bytes
System.out.println("Size: " + ____.____() + " bytes");
try {
// Create a Path object from the file path
Path path = Paths.____(filePath);
List lines = Files.readAllLines(path);
System.out.println("Total lines: " + lines.size());
System.out.println("Header: " + lines.get(0));
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}