Java JFileChooser saveToFile(Object obj)

Here you can find the source of saveToFile(Object obj)

Description

save To File

License

Open Source License

Declaration

public static String saveToFile(Object obj) 

Method Source Code


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

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.swing.*;
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.io.*;

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

    public static String saveToFile(Object obj) {
        return saveToFile(toJson(obj));
    }//from w ww  .  j a va 2 s . c  o  m

    public static String saveToFile(String json) {
        JFileChooser fileChooser = new JFileChooser(lastTouchedDirectory) {
            @Override
            protected JDialog createDialog(Component parent) throws HeadlessException {
                JDialog dialog = super.createDialog(parent);
                dialog.setAlwaysOnTop(true);
                dialog.setModalityType(ModalityType.APPLICATION_MODAL);
                dialog.setModal(true);
                return dialog;
            }
        };
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setDialogTitle("Save As");
        fileChooser.setApproveButtonText("Save");
        if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            lastTouchedFileName = fileChooser.getSelectedFile().getName();
            lastTouchedDirectory = fileChooser.getSelectedFile().getParent();
            try {
                FileWriter writer = new FileWriter(fileChooser.getSelectedFile());
                writer.write(json);
                writer.close();
                return json;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. save(JFileChooser fileChooser, Runnable action)
  2. saveFile(Component parent, File defaultFile)
  3. saveFile(String title, File currentDir, javax.swing.filechooser.FileFilter filter)
  4. saveObject(final Object content, final String description, final String extension, final File file)
  5. saveSystemFiles(Component owner)
  6. select_file(Component parent, boolean show_save)
  7. selectAndSaveToFile(String content, Component parent)
  8. selectDirectory(Component component, String name, File pathToUse)
  9. selectedFiles(JFileChooser chooser)