Advertisement
Guest User

Untitled

a guest
Apr 20th, 2020
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1.  
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.util.Scanner;
  7.  
  8. public class FileHelper {
  9.  
  10. /**
  11. * Opens a text file and reads it's contents as a String
  12. *
  13. * @param filePath The path to the file to be opened
  14. */
  15. public static String openTextFile(String filePath) {
  16.  
  17. // You can use the Scanner class to read input from a file
  18. Scanner scanner;
  19. // The StringBuilder class is efficient for string concatenation
  20. StringBuilder sb = new StringBuilder();
  21.  
  22. try {
  23. scanner = new Scanner(new File(filePath));
  24. while (scanner.hasNextLine()) {
  25. sb.append(scanner.nextLine() + "\n");
  26. }
  27. scanner.close();
  28. } catch (Exception e) {
  29. //e.printStackTrace();
  30. System.out.println("\n\n\nUnable to openTextFile: " + filePath + " - maybe it hasn't been created yet???");
  31. }
  32.  
  33. return sb.toString();
  34.  
  35. }
  36.  
  37. /**
  38. * Saves string data to a file on the file system.
  39. *
  40. * @param filePath The path to the file to be saved
  41. * @param fileData The data to put in the file
  42. */
  43. public static boolean saveTextFile(String filePath, String fileData){
  44. try{
  45.  
  46. PrintWriter output = new PrintWriter(filePath);
  47. output.println(fileData);
  48. output.close();
  49. return true;
  50. }catch(Exception e){
  51. System.out.println("Error: " + e.getMessage());
  52. return false;
  53. }
  54. }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement