Advertisement
TerrificTable55

Untitled

Nov 13th, 2022
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. public class FileIOUtils {
  2.  
  3.     /**
  4.      * Write JsonObject to file
  5.      * @param filepath String filepath
  6.      * @param contents JsonObject contents
  7.      */
  8.     public static void writeFile(String filepath, JsonObject contents) {
  9.         writeFile(filepath, JsonUtils.formatJsonObjectToString(contents));
  10.     }
  11.  
  12.     /**
  13.      * Write stuff to a file
  14.      * @param filepath the file
  15.      * @param contents what to write into the file
  16.      */
  17.     public static void writeFile(String filepath, String contents) {
  18.         try {
  19.             FileWriter fw = new FileWriter(filepath);
  20.             fw.write(contents);
  21.             fw.close();
  22.         } catch (Exception e) {
  23.             e.printStackTrace();
  24.         }
  25.     }
  26.  
  27.     /**
  28.      * Read content of a file
  29.      * @param filepath the file to read from
  30.      * @return the files contents
  31.      */
  32.     public static String readFile(String filepath) {
  33.         StringBuilder result = new StringBuilder();
  34.         try {
  35.             Scanner scanner = new Scanner(new java.io.File(filepath));
  36.             while (scanner.hasNextLine()) {
  37.                 result.append(scanner.nextLine());
  38.             }
  39.             scanner.close();
  40.         } catch (Exception e) {
  41.             e.printStackTrace();
  42.         }
  43.         return result.toString();
  44.     }
  45.  
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement