Here you can find the source of selectAndSaveToFile(String content, Component parent)
Parameter | Description |
---|---|
content | Content which should be written to a file |
parent | Reference to parent component (can be null) |
Parameter | Description |
---|---|
IOException | Throws an IOException when file is not accessible or when anerror occurred during the write process |
public static void selectAndSaveToFile(String content, Component parent) throws IOException
//package com.java2s; // License as published by the Free Software Foundation; either import java.awt.Component; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class Main { /**// w w w .jav a 2 s . c o m * Show dialog for selecting a file and write file content to file * * @param content * Content which should be written to a file * * @param parent * Reference to parent component (can be null) * * @throws IOException * Throws an IOException when file is not accessible or when an * error occurred during the write process */ public static void selectAndSaveToFile(String content, Component parent) throws IOException { // Create file save dialog @SuppressWarnings("serial") JFileChooser fileSaveDialog = new JFileChooser() { @Override public void approveSelection() { File f = getSelectedFile(); if (f.exists() && getDialogType() == SAVE_DIALOG) { int result = JOptionPane.showConfirmDialog(this, "File already exists, overwrite?", "Existing file", JOptionPane.YES_NO_OPTION); switch (result) { case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: return; } } super.approveSelection(); } }; fileSaveDialog.setFileSelectionMode(JFileChooser.FILES_ONLY); // Show file save dialog and write content to file int dialogResult = fileSaveDialog.showSaveDialog(parent); if (dialogResult == JFileChooser.APPROVE_OPTION) { File file = fileSaveDialog.getSelectedFile(); // Open file for writing and write content writeToFile(new FileWriter(file), content); } } /** * Directly writes content to a given writer object * * @param writer * A writer object * * @param content * Content which should be written * * @throws IOException * Throws an IOException when an error occurred during the write * process */ private static void writeToFile(Writer writer, String content) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(writer); // Write content and close steam bufferedWriter.write(content); bufferedWriter.close(); } }