SHARE
TWEET

GsonIO.java

a guest Sep 23rd, 2016 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.File;
  2. import java.io.FileReader;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5.  
  6. import org.bukkit.craftbukkit.libs.com.google.gson.Gson;
  7. import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder;
  8.  
  9. public class GsonIO {
  10.     public static void createFile(String dir, Object obj){
  11.         File file = new File(dir);
  12.         if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
  13.         try{
  14.             FileWriter writer = null;
  15.             try{
  16.                 writer = new FileWriter(file);
  17.                 GsonBuilder builder = new GsonBuilder();
  18.                 builder.setPrettyPrinting();
  19.                 Gson gson = builder.create();
  20.                 gson.toJson(obj, writer);
  21.             }
  22.             finally{
  23.                 if (writer != null) writer.close();
  24.             }
  25.         }
  26.         catch (IOException e){
  27.             e.printStackTrace();
  28.         }
  29.     }
  30.    
  31.     public static <T> T getObject(File file, Class<T> type){
  32.         try {
  33.             FileReader reader = null;
  34.             try{
  35.                 reader = new FileReader(file);
  36.                 if (!file.exists()) return null;
  37.                 GsonBuilder builder = new GsonBuilder();
  38.                 Gson gson = builder.create();
  39.                 return gson.fromJson(reader, type);
  40.             }
  41.             finally{
  42.                 if (reader != null) reader.close();
  43.             }
  44.         }
  45.         catch (Exception e){
  46.             e.printStackTrace();
  47.             return null;
  48.         }
  49.     }
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top