Practical Code Examples
Comprehensive CSV Appending Scenarios
1. Basic User Data Logging
public class UserLogger {
private static final String CSV_FILE = "/home/labex/users.csv";
public void logUser(String name, int age, String email) {
try (FileWriter fw = new FileWriter(CSV_FILE, true)) {
fw.append(String.format("%s,%d,%s\n", name, age, email));
} catch (IOException e) {
System.err.println("Error logging user: " + e.getMessage());
}
}
}
2. Transaction Record Management
public class TransactionRecorder {
private static final String TRANSACTION_FILE = "/home/labex/transactions.csv";
public void recordTransaction(double amount, String type, LocalDateTime timestamp) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(TRANSACTION_FILE, true))) {
String transactionData = String.format("%.2f,%s,%s\n", amount, type, timestamp);
bw.write(transactionData);
} catch (IOException e) {
System.err.println("Transaction recording failed: " + e.getMessage());
}
}
}
CSV Appending Workflow
graph TD
A[Input Data] --> B[Validate Data]
B --> C[Format Data]
C --> D[Append to CSV]
D --> E[Error Handling]
3. Advanced Error-Resistant CSV Appending
public class RobustCSVAppender {
public void safeAppend(String filePath, List<String> dataLines) {
try {
Path path = Paths.get(filePath);
// Ensure file exists
if (!Files.exists(path)) {
Files.createFile(path);
}
// Append lines with validation
Files.write(path,
dataLines.stream()
.filter(this::isValidData)
.map(line -> line + "\n")
.collect(Collectors.toList()),
StandardOpenOption.APPEND
);
} catch (IOException e) {
System.err.println("CSV Append Error: " + e.getMessage());
}
}
private boolean isValidData(String data) {
return data != null && !data.trim().isEmpty();
}
}
CSV Appending Method Comparison
Method |
Complexity |
Performance |
Use Case |
FileWriter |
Low |
Basic |
Small files |
BufferedWriter |
Medium |
Efficient |
Medium files |
Files.write() |
High |
Robust |
Large, complex files |
4. Batch Processing Example
public class BatchCSVProcessor {
public void processBatchData(List<String[]> dataList, String outputFile) {
try (PrintWriter pw = new PrintWriter(new FileWriter(outputFile, true))) {
dataList.forEach(data ->
pw.println(String.join(",", data))
);
} catch (IOException e) {
System.err.println("Batch processing failed: " + e.getMessage());
}
}
}
Best Practices for LabEx Developers
- Always validate input data
- Use appropriate exception handling
- Choose the right appending method
- Consider file size and performance
- Implement logging mechanisms
Error Handling Strategy
graph LR
A[Potential Error] --> B{Error Type}
B --> |File Not Found| C[Create File]
B --> |Permission Issue| D[Log Error]
B --> |Data Validation| E[Filter Invalid Data]
Conclusion
These practical examples demonstrate various approaches to appending data to CSV files in Java, showcasing flexibility and robustness in different scenarios. By understanding these techniques, developers can efficiently manage CSV file operations in their applications.