Java JFileChooser write(File file, String text)

Here you can find the source of write(File file, String text)

Description

write

License

Open Source License

Declaration

public static void write(File file, String text) throws IOException 

Method Source Code


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

import java.io.*;
import java.nio.file.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
    public static void write(Path path, String text) throws IOException {
        Files.write(path, text.getBytes("ASCII"));
    }//  w  w  w. j a v  a2  s. c o m

    public static void write(File file, String text) throws IOException {
        write(file.toPath(), text);
    }

    public static void write(JFrame frame, String ext, String desc, String text) throws IOException {
        File file = findFileSave(frame, ext, desc);

        if (file == null) {
            return;
        }

        write(file, text);
    }

    public static void write(JFrame frame, String ext, String desc, byte[] data) throws IOException {
        File file = findFileSave(frame, ext, desc);

        if (file == null) {
            return;
        }

        Files.write(file.toPath(), data);
    }

    public static File findFileSave(JFrame frame, String ext, String desc) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileNameExtensionFilter(desc, ext));

        if (chooser.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION) {
            return null;
        }

        return getSelectedFileWithExtension(chooser);
    }

    /**
     * Returns the selected file from a JFileChooser, including the extension from
     * the file filter.
     * From: http://stackoverflow.com/a/18984561
     */
    public static File getSelectedFileWithExtension(JFileChooser c) {
        File file = c.getSelectedFile();
        if (c.getFileFilter() instanceof FileNameExtensionFilter) {
            String[] exts = ((FileNameExtensionFilter) c.getFileFilter()).getExtensions();
            String nameLower = file.getName().toLowerCase();
            for (String ext : exts) { // check if it already has a valid extension
                if (nameLower.endsWith('.' + ext.toLowerCase())) {
                    return file; // if yes, return as-is
                }
            }
            // if not, append the first extension from the selected filter
            file = new File(file.toString() + '.' + exts[0]);
        }
        return file;
    }
}

Related

  1. setFile(File file, JFileChooser chooser)
  2. setFileChooserFilters(JFileChooser fileDlg, String filters, int selectIndex)
  3. setSelectedFile(JFileChooser chooser, File file)
  4. SHOW_JFILECHOOSER(String title, String approvetext, int fileselectionmode, boolean multiselection)
  5. showFileChooserLoop(Component parentComponent, JFileChooser chooser)
  6. writeOnFile(String row)
  7. writeStringToFile(String output)