Java JFileChooser loadFileAs(Class clazz, String json)

Here you can find the source of loadFileAs(Class clazz, String json)

Description

load File As

License

Open Source License

Declaration

public static <T> T loadFileAs(Class<T> clazz, String json) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.swing.*;

import java.io.*;

public class Main {
    public static String lastTouchedFileName = "";
    private static String lastTouchedDirectory = null;
    private static final ObjectMapper mapper = new ObjectMapper();

    public static <T> T loadFileAs(Class<T> clazz) {
        String file = loadFile();
        if (file == null || file.length() <= 0) {
            return null;
        } else {/*from www . j a v a2s . c  om*/
            return loadFileAs(clazz, file);
        }
    }

    public static <T> T loadFileAs(Class<T> clazz, File file) {
        return loadFileAs(clazz, loadFile(file));
    }

    public static <T> T loadFileAs(Class<T> clazz, String json) {
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String loadFile() {
        JFileChooser fileChooser = new JFileChooser(lastTouchedDirectory);
        fileChooser.setApproveButtonText("Load");

        if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            lastTouchedFileName = selectedFile.getName();
            lastTouchedDirectory = selectedFile.getParent();
            return loadFile(selectedFile);
        }
        return null;
    }

    public static String loadFile(File file) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            StringBuffer json = new StringBuffer();
            String line = reader.readLine();
            while (line != null) {
                json.append(line);
                line = reader.readLine();
            }
            if (json.length() > 0) {
                return json.toString();
            } else {
                System.out.println("File was empty. Could not load.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }
}

Related

  1. importFile(JFileChooser jFileChooser)
  2. initFileChooser(JFileChooser fileChooser, FileFilter filter)
  3. isDriveTraversable(File drive)
  4. loadFile()
  5. loadFile(Component parent, String title)
  6. makeFileChooser()
  7. openDataFileChooser(Component com)
  8. openFile()
  9. openFile(String fileExtension)