Java JFileChooser loadFile()

Here you can find the source of loadFile()

Description

load File

License

Open Source License

Declaration

public static String loadFile() 

Method Source Code


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

import javax.swing.*;

import java.io.*;

public class Main {
    public static String lastTouchedFileName = "";
    private static String lastTouchedDirectory = 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);
        }/*from   w  w  w .  j  a  v  a  2s . c o  m*/
        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. getTextFileChooser()
  2. getXmlFileChooser()
  3. importFile(JFileChooser jFileChooser)
  4. initFileChooser(JFileChooser fileChooser, FileFilter filter)
  5. isDriveTraversable(File drive)
  6. loadFile(Component parent, String title)
  7. loadFileAs(Class clazz, String json)
  8. makeFileChooser()
  9. openDataFileChooser(Component com)