Results 1 to 5 of 5
  1. #1
    masa is offline Member
    Join Date
    Nov 2008
    Posts
    21
    Rep Power
    0

    Default save file based on file extension

    hi everyone
    i am able to write a program for opening a save dialog box and give the filename with extension and click on save to save it. but when i give the file name without extension and select the file type whatever it may be it is saying that file in an unknown format. i want to save the file based on the file type choosen and with/without specifying the extension..hope you got the point....
    here is the class i have done with....


    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class FileChooseApp extends JFrame implements ActionListener{
    JMenuItem fMenuOpen = null;
    JMenuItem fMenuSave = null;
    JMenuItem fMenuClose = null;
    JTextArea fTextArea;
    JavaFilter fJavaFilter = new JavaFilter ();
    File fFile = new File ("default.java");
    FileChooseApp (String title) {
    super (title);
    Container content_pane = getContentPane ();
    content_pane.setLayout ( new BorderLayout () );
    fTextArea = new JTextArea ("");
    content_pane.add ( fTextArea, "Center");
    JMenu m = new JMenu ("File");
    m.add (fMenuOpen = makeMenuItem ("Open"));
    m.add (fMenuOpen = makeMenuItem ("Save"));
    m.add (fMenuClose = makeMenuItem ("Quit"));
    JMenuBar mb = new JMenuBar ();
    mb.add (m);
    setJMenuBar (mb);
    setSize (400,400);
    }
    public void actionPerformed ( ActionEvent e ) {
    boolean status = false;
    String command = e.getActionCommand ();
    if (command.equals ("Open")) {
    status = openFile ();
    if (!status)
    JOptionPane.showMessageDialog (
    null,
    "Error opening file!", "File Open Error",
    JOptionPane.ERROR_MESSAGE
    );
    } else if (command.equals ("Save")) {
    status = saveFile ();
    if (!status)
    JOptionPane.showMessageDialog (
    null,
    "IO error in saving file!!", "File Save Error",
    JOptionPane.ERROR_MESSAGE
    );
    } else if (command.equals ("Quit") ) {
    dispose ();
    }
    }
    private JMenuItem makeMenuItem (String name) {
    JMenuItem m = new JMenuItem (name);
    m.addActionListener (this);
    return m;
    }
    boolean openFile () {
    JFileChooser fc = new JFileChooser ();
    fc.setDialogTitle ("Open File");
    fc.setFileSelectionMode ( JFileChooser.FILES_ONLY);
    fc.setCurrentDirectory (new File ("."));
    fc.setFileFilter (fJavaFilter);
    int result = fc.showOpenDialog (this);
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {

    fFile = fc.getSelectedFile ();
    String file_string = readFile (fFile);
    if (file_string != null)
    fTextArea.setText (file_string);
    else
    return false;
    } else {
    return false;
    }
    return true;
    }
    boolean saveFile () {
    File file = null;
    JFileChooser fc = new JFileChooser ();
    javax.swing.filechooser.FileFilter filter=null;
    fc.setCurrentDirectory (new File ("."));
    fc.setFileSelectionMode(JFileChooser.FILES_AND_DIR ECTORIES);
    fc.addChoosableFileFilter(filter);
    filter = fc.getFileFilter();
    fc.setFileFilter (fJavaFilter);
    fc.setSelectedFile (fFile);
    int result = fc.showSaveDialog (this);
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
    fFile = fc.getSelectedFile ();
    if (fFile.exists ()) {
    int response = JOptionPane.showConfirmDialog (null,
    "Overwrite existing file?","Confirm Overwrite",
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE);
    if (response == JOptionPane.CANCEL_OPTION) return false;
    }
    return writeFile (fFile, fTextArea.getText ());
    } else {
    return false;
    }
    }

    public String readFile (File file) {
    StringBuffer fileBuffer;
    String fileString=null;
    String line;
    try {
    FileReader in = new FileReader (file);
    BufferedReader dis = new BufferedReader (in);
    fileBuffer = new StringBuffer () ;

    while ((line = dis.readLine ()) != null) {
    fileBuffer.append (line + "\n");
    }

    in.close ();
    fileString = fileBuffer.toString ();
    }
    catch (IOException e ) {
    return null;
    }
    return fileString;
    }
    public static boolean writeFile (File file, String dataString) {
    try {
    PrintWriter out =
    new PrintWriter (new BufferedWriter (new FileWriter (file)));
    out.print (dataString);
    out.flush ();
    out.close ();
    }
    catch (IOException e) {
    return false;
    }
    return true;
    }
    public static void main (String [] args) {
    String title="Frame Test";
    if (args.length != 0) title = args[0];
    FileChooseApp f = new FileChooseApp (title);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
    f.setVisible (true);
    }

    }

    ******************
    JavaFilter.java
    *****************

    import javax.swing.*;
    import java.io.*;
    public class JavaFilter extends javax.swing.filechooser.FileFilter
    {
    public boolean accept (File f) {
    return f.getName ().toLowerCase ().endsWith (".java")|| f.isDirectory ();
    }
    public String getDescription () {
    return "Java files (*.java)" ;
    }
    }

    the above program JavaFilter is allowing to show only "Java Files (*.java)" in the file type combo box. i want to show more than one file type as html files,text files and based on the file type if i give only the name in the filename textfield it should save it in that form....can anyone help ....................

  2. #2
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    There is no magic way of converting to arbitrary file types by extension in general. Programs that do that usually have a hell of a lot of code implemented for that functionality.

    That said, some of the Java APIs almost do that for certain types of files. For example, ImageIO does that for jpeg, png, bmp, (and gif?) formats. The sound API does that for a limited set of sound files. But in general, you have to write a bunch of code.

  3. #3
    masa is offline Member
    Join Date
    Nov 2008
    Posts
    21
    Rep Power
    0

    Default save file based on file extension

    i agree with you, but i want to know how to catch the event when save button is clicked on the save dialog box.if i can do so then i can write bunch of code to save the file as per file extension. where to write the logic........

  4. #4
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    Well, if you use a JFileChooser, it returns the file name selected. To determine the extension on the file, you can use the String.split command

    Java Code:
    JFileChooser chooser = JFileChooser(...
    ...
    
    String[] splits = chooser.getSelectedFile().getName().split("\\.");
    
    String extension = splits[splits.length-1];
    ...ignoring error checking and intermediate rigamarole.

  5. #5
    Leejjon is offline Member
    Join Date
    May 2010
    Posts
    1
    Rep Power
    0

    Default

    I needed the same functionality and found this topic through the internet. After trying out some things I managed to find a solution.

    Create your own FileFilter class like I created:
    Java Code:
    public class PNGFileFilter extends FileFilter implements FilenameFilter{
    	public static final String PNG_EXTENSION = ".png";
    	public static final String PNG_DESCRIPTION = "PNG Image";
    	public boolean accept(File dir, String name)	{
    		try
    		{
    			if (name != null)
    			{
    				return name.endsWith(PNG_EXTENSION);
    			}
    		}
    		catch (Exception e)
    		{
    		}
    		return false;
    	}
    	public boolean accept(File file)	{
    		try
    		{
    			//check if the file is not nule and if the file is a directory
    			if (file != null && file.isDirectory())
    			{
    				return true;
    			}
    			//check if the file extension is ".pdf"
    			if (file != null && file.getCanonicalPath() != null)
    			{
    				return file.getCanonicalPath().endsWith(PNG_EXTENSION);
    			}
    		}
    		catch (Exception e)
    		{
    		}
    		return false;
    	}
    
    	public String getDescription(){
    		return PNG_DESCRIPTION;
    	}
    }
    Initialising the JFileChooser();
    Java Code:
    		JFileChooser kbFileDialogWin = new JFileChooser();
    		kbFileDialogWin.setAcceptAllFileFilterUsed(false);
    		kbFileDialogWin.addChoosableFileFilter(new PDFFileFilter());
    		kbFileDialogWin.addChoosableFileFilter(new PNGFileFilter());
    		kbFileDialogWin.setDialogType(JFileChooser.SAVE_DIALOG);
    What to do after selecting a file:
    Java Code:
    		int returnVal = kbFileDialogWin.showSaveDialog(theframe);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    					String exportPath = kbFileDialogWin.getSelectedFile().getAbsolutePath();
    					FileFilter selectedFileType = kbFileDialogWin.getFileFilter();
    					// The getFileFilter should be renamed to getSelectedFileFilter, since it returns the selected one if there are more then one.
    					if(selectedFileType.getDescription().equals(PNGFileFilter.PNG_DESCRIPTION)){
    					// TODO: Save the file as png since now you know for sure it's a PNG
    }
    Hope you guys won't be annoyed with me bumping old topics but at least if people wonder on how to do this they will find this topic :p
    Last edited by Leejjon; 05-11-2010 at 11:26 AM.

Similar Threads

  1. File Extension Filter
    By heartysnowy in forum New To Java
    Replies: 9
    Last Post: 10-09-2010, 01:33 PM
  2. how to save file..
    By jont717 in forum New To Java
    Replies: 2
    Last Post: 02-12-2009, 11:33 PM
  3. how to save Interface (file extension)
    By shaggyoo7 in forum New To Java
    Replies: 9
    Last Post: 01-10-2009, 09:07 AM
  4. Replies: 0
    Last Post: 04-05-2008, 10:13 AM
  5. Regex for file extension
    By gapper in forum New To Java
    Replies: 1
    Last Post: 01-31-2008, 03:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •