1. import java.io.BufferedWriter;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Path;
  5. import java.nio.file.Paths;
  6. import java.util.List;
  7. public class UserDataExporter {
  8. /**
  9. * Exports user data to a file for diagnostics.
  10. * @param userData A list of user data objects.
  11. * @param outputFilePath The path to the output file.
  12. * @return True if the export was successful, false otherwise.
  13. */
  14. public boolean exportUserData(List<UserData> userData, String outputFilePath) {
  15. try {
  16. // Create the output file
  17. Path filePath = Paths.get(outputFilePath);
  18. if (Files.exists(filePath)) {
  19. Files.deleteIfExists(filePath); // Overwrite if exists
  20. }
  21. // Open the file for writing
  22. try (BufferedWriter writer = Files.newBufferedWriter(filePath)) {
  23. // Write user data to the file
  24. for (UserData user : userData) {
  25. writer.write(user.toString() + "\n"); // Assuming UserData has a toString() method
  26. }
  27. } catch (IOException e) {
  28. System.err.println("Error writing to file: " + e.getMessage());
  29. return false; // Indicate failure
  30. }
  31. return true; // Indicate success
  32. } catch (Exception e) {
  33. System.err.println("An unexpected error occurred: " + e.getMessage());
  34. return false;
  35. }
  36. }
  37. // Placeholder for UserData class
  38. public static class UserData {
  39. private String name;
  40. private String email;
  41. public UserData(String name, String email) {
  42. this.name = name;
  43. this.email = email;
  44. }
  45. @Override
  46. public String toString() {
  47. return "Name: " + name + ", Email: " + email;
  48. }
  49. }
  50. public static void main(String[] args) {
  51. // Example usage
  52. List<UserData> data = List.of(
  53. new UserData("Alice", "alice@example.com"),
  54. new UserData("Bob", "bob@example.com")
  55. );
  56. String outputFile = "user_data.txt";
  57. UserDataExporter exporter = new UserDataExporter();
  58. boolean success = exporter.exportUserData(data, outputFile);
  59. if (success) {
  60. System.out.println("User data exported successfully to " + outputFile);
  61. } else {
  62. System.err.println("User data export failed.");
  63. }
  64. }
  65. }

Add your comment