import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class UserDataExporter {
/**
* Exports user data to a file for diagnostics.
* @param userData A list of user data objects.
* @param outputFilePath The path to the output file.
* @return True if the export was successful, false otherwise.
*/
public boolean exportUserData(List<UserData> userData, String outputFilePath) {
try {
// Create the output file
Path filePath = Paths.get(outputFilePath);
if (Files.exists(filePath)) {
Files.deleteIfExists(filePath); // Overwrite if exists
}
// Open the file for writing
try (BufferedWriter writer = Files.newBufferedWriter(filePath)) {
// Write user data to the file
for (UserData user : userData) {
writer.write(user.toString() + "\n"); // Assuming UserData has a toString() method
}
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
return false; // Indicate failure
}
return true; // Indicate success
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
return false;
}
}
// Placeholder for UserData class
public static class UserData {
private String name;
private String email;
public UserData(String name, String email) {
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "Name: " + name + ", Email: " + email;
}
}
public static void main(String[] args) {
// Example usage
List<UserData> data = List.of(
new UserData("Alice", "alice@example.com"),
new UserData("Bob", "bob@example.com")
);
String outputFile = "user_data.txt";
UserDataExporter exporter = new UserDataExporter();
boolean success = exporter.exportUserData(data, outputFile);
if (success) {
System.out.println("User data exported successfully to " + outputFile);
} else {
System.err.println("User data export failed.");
}
}
}
Add your comment