Reading a File
About
Read a File Based on Its Location
1. Reading a File from the resources Folder (Classpath)
resources Folder (Classpath)Example
import org.springframework.core.io.ClassPathResource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public String readFileFromClasspath() throws IOException {
ClassPathResource resource = new ClassPathResource("data/sample.txt");
try (InputStream inputStream = resource.getInputStream()) {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
}2. Reading a File from File System (Absolute or Relative Path)
Example
3. Reading a File from a System Property or Environment Variable
Example
4. Reading a File from a URL or Remote Source
Example
5. Reading a File Uploaded via API (MultipartFile)
MultipartFile)Example
6. Reading a File from a Remote SFTP Location
Read a File Based on Reading Technique
1. Reading Whole File into a String
Example
2. Reading Line by Line using BufferedReader
BufferedReaderExample
3. Reading Using Java 8 Streams
Example
4. Reading Using Scanner
ScannerExample
5. Reading Using Spring’s Resource API
Resource APIExample
6. Reading a File into Byte Array
Example
Best Practices based on File Size
1. Small Files (up to a few KB)
Characteristics
Best Practices
Example
Recommendation
2. Medium Files (few KB to several MB)
Characteristics
Best Practices
Example
Recommendation
3. Large Files (tens or hundreds of MB and above)
Characteristics
Best Practices
Example
Recommendation
4. Uploaded Files (via REST API)
Best Practices
Example
5. Binary Files (PDF, image, Excel, etc.)
Best Practices
Example
Why BufferedReader is Preferred for Large Files ?
BufferedReader is Preferred for Large Files ?1. Low Memory Usage
2. Buffered I/O Improves Performance
3. Line-by-Line Processing
4. Suitable for Sequential Processing
5. Avoids OutOfMemoryError
Last updated