JFile Chooser - Add automatic file extension while Saving

Hello,
I have a JFileChooser, which I use for saving output from my program.
Problem is whenever I save a new file I have to manually specify its extension, otherwise I get an undefined file with no extensions.
I want my default extension to be ".txt".
Any ideas on what method to use? Is this a trivial issue or a complicated one?
Thank you,
Berkan

What about this? Not tested.
import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;
public class FilenameGetter {
    private JFileChooser chooser = new JFileChooser();
    public File getFileToSaveTxt(Component parent) {
     if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(parent)) {
         File chosenFile = chooser.getSelectedFile();
         if (chosenFile.getName().endsWith(".txt")) {
          return chosenFile;
         } else {
          return new File(chosenFile.getParentFile(), chosenFile
               .getName()
               + ".txt");
     } else {
         return null;
}Piet

Similar Messages

  • Marking a file extension during saving???

    Hi.
    The problem is, when a file is going to be saved, how can I do such a improvisation like a "save as" dialog?
    To avoid the "poor" technique of, user typing the extension, can do a something like a "save as" option in the JFileChooser saveDialog(), to offer a list of extensions and when user pick up one, to add it to the file name path, during file saving ?
    Thanks!

    Here is the solution I came up with. It will add the file extension if a FileExtensionFilter is selected, and you can set it to warn on write over
    * Created on May 17, 2005 by @author Tom Jacobs
    package tjacobs.ui.swing_ex;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.File;
    import javax.swing.JOptionPane;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileSystemView;
    import tjacobs.ui.FSFileView;
    import tjacobs.ui.fc.FileExtensionFilter;
    public class JFileChooser extends javax.swing.JFileChooser {
         private static final long serialVersionUID = 1L;
         private boolean mWarnOnWriteOver = false;
         private boolean mAncestorNull = false;
         public JFileChooser() {
              super();
              init();
         private void init() {
              setFileView(new FSFileView());
         public JFileChooser(String arg0) {
              super(arg0);
              init();
         public JFileChooser(File arg0) {
              super(arg0);
              init();
         public JFileChooser(FileSystemView arg0) {
              super(arg0);
              init();
         public JFileChooser(File arg0, FileSystemView arg1) {
              super(arg0, arg1);
              init();
         public JFileChooser(String arg0, FileSystemView arg1) {
              super(arg0, arg1);
              init();
         public boolean getWarnOnWriteOver() {
              return mWarnOnWriteOver;
         public void setWarnOnWriteOver(boolean b) {
              mWarnOnWriteOver = b;
              if (b) {
                   addPropertyChangeListener(new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent pe) {
                             //System.out.println("Here");
                             //System.out.println(pe.getPropertyName() + ": " + pe.getNewValue());
                             if (pe.getPropertyName().equals("ancestor") && pe.getNewValue() == null) {
                                  mAncestorNull = true;
                                  return;
                             mAncestorNull = false;
         public File getSelectedFile() {
              File f = super.getSelectedFile();
              if (f == null) return f;
              if (getDialogType() == javax.swing.JFileChooser.SAVE_DIALOG && f.getName().indexOf(".") == -1) {
                   //check if it's using file extension filter. If so, add the filter extension
                   FileFilter ff = getFileFilter();
                   if (ff instanceof FileExtensionFilter) {
                        String ending = ((FileExtensionFilter)ff).getType();
                        f = new File(f.getParent(), f.getName() + "." + ending);
              // now check if it's overwriting another file
              if (mWarnOnWriteOver && mAncestorNull) {
                   if (f.exists()) {
                        int ans = JOptionPane.showConfirmDialog(null, "" + f.getName() + " exists. Overwrite?", "Save Over Existing File", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (ans == JOptionPane.OK_OPTION)
                             return f;
                        return null;
              return f;
    }

  • How to retain file name while saving file on archive servers

    Hi Experts,
    I am using function modules:
    ARCHIVOBJECT_CREATE_TABLE and ARCHIV_CONNECTION_INSERT for inserting a file to archive server and for linking it with a document.
    Then I am reading the URL using FM: SCMS_AO_URL_READ. When I get this URL and download that file, the file name will be always defaulted to 'pclHTTP.dll'. I debugged these FMs to a certain extent and found that this name comes from CREP_HTTP-HTTP_SCRPT table.
    Is there any way I can retain the file name while saving it so that when I read the URL it has correct file name in it?
    Please help.
    Regards,
    Anand Kolte

    Hi Max,
    In case when downloading one file it is fine. But if I want to download 10 files at once and later if I go to my downloads, every file will be having similar name. Unless we open the file, we cannot know what file it is.
    Regards,
    Anand

  • Mistakenly change file extension while in disk use mode

    I made the mistake of changing the file extension of a file on my Nano (5G) while it was in "disk use" mode. When I unplugged the device and later plugged it in, the modified file was gone. Does the Nano treat unrecognized files as non-existant? I tried using Windows Explorer to find the file, but nothing was there. Also, the overall memory used on the Nano has decreased by what I would guess is the same amount as the missing file. I'd like to get my file back. Any suggestions?

    Processing Raw in a 3rd Party Application
    You can also process your Raw with a 3rd Party app like ACR or Photoshop. But iPhoto does not handle this gracefully and it's a bit of a kludge.
    First off set your preferred app as an external editor in iPhoto:
    You can set Photoshop (or any image editor) as an external editor in iPhoto. (Preferences -> General -> Edit Photo: Choose from the Drop Down Menu.) This way, when you double click a pic to edit in iPhoto it will open automatically in Photoshop or your Image Editor, and when you save it it's sent back to iPhoto automatically. This is the only way that edits made in another application will be displayed in iPhoto.
    Note that iPhoto sends a copy+ of the file to Photoshop, so when you save be sure to use the Save command, not Save As... If you use Save As then you're creating a new file and iPhoto has no way of knowing about this new file. iPhoto is preserving your original anyway.
    Next: In the iPhoto Preferences -> Advanced, elect to use Raw with your External editor:
    Uploaded with plasq's Skitch!
    Now when you go to edit the Raw it will be sent to your external editor.
    Now for the kludge:
    You cannot save a Raw. The work you do must be output to a new file, in a new format (jepg, tiff, whatever). However, as the External Editor is making this new file iPhoto has no knowledge of its existence. Therefore you *must save it to the desktop and then import it back to iPhoto as a new file*.
    This means that you will have your Original Raw and the processed version in iPhoto but they will not be recognised as version and original. iPhoto will see them as two separate shots.

  • Can you add new file extensions to be treated as C source?

    Hi, using Sun Studio 9, is it possible to add a new file extension to those treated as C sources? I can see how to do it for header files (Options -> IDE Configuration -> System -> Object Types -> C and C++ Header Data Objects -> Extensions and MIME types) but this option is not available for C files.
    In case anyone's wondering why you'd want to do this: we use .pc extensions for C files containing embedded SQL statements. It's then pretty simple to make a .pc.c rule in makefiles to run the pre-compiler.

    >What do you mean Sandee?<br /><br />Robert,<br /><br />Sandee's comment did come across as a bit strong, eh. InDesign is better than Quark  for the most part. (Hey,even Quark has it's good points. <g>) But they are different and preconceptions of how to do certain things can hinder a user from using the program to it's best advantage. This goes both ways, but long time Quark users will almost certainly have developed some bad habits that should be broken if using InDesign. [check out theInDesigner.com podcasts. the first few are audio only but the first one in particular deals with this idea, and others reinforce it with specifics.]<br /><br />Your concern about Quark Project files does not fit into this catagory though. You will not find a comparable feature in ID. But I don't think you'll miss it as much as you think.<br /><br />I can't answer your questions about Bridge and Version Cue. I have no experience with them. [there are videocasts on Adobe TV that may give you an idea of how useful Bridge can be. Cafe Fibonacci Ep1, touches on it, Lazy Designer has a couple of episodes that show some not so obvious features.] Essentially Bridge is a common repository for all your files, and that can include your colleagues. But it's more than a way to catalogue and codify your files, you can access the rest of the suite from Bridge, you can even access specific functions of the other applications directly within Bridge.<br /><br />Version Cue manages projects. It keeps track of who did what to where and what version is current. It also allows you to submit different versions for consideration and revert specific items of your layout to previous versions  or is that Bridge? Hopefully someone with a better grasp of Bridge and Version Cue will come to your rescue. But it's obvious that there is a lot of work group functionality built in to CS.

  • Saving attachments on Snow leopard mail loses file extension when saving over an existing document

    Saving attachments on Snow leopard mail loses the file extension when clicking on an existing file to copy the name. Is there something I can switch on in the preferences to fix this?

    I work for a publishing company where our clients send their copy to us in Word documents. We might have several versions sent to us before the final version comes in.
    It is instances like this where we want to overwrite a document on the server with the most up-to-date version (which is usually named differently to the original file). We really don't want to clutter the folder with lots of different revisions. The quick way to do this is to click on the document we are replacing (this copies the document name). Previous versions of OSX Mail used to keep the file extension but Snow Leopard seems to remove it.
    It's annoying as there is no particular logic to this. We just have to manually type ".doc" at the end of the document.
    Incidentally, this happens with any attachment file type.

  • Automatic File Extension in BrowseForSave

    Is there a way to set the extension of a file using
    flash.FileSystems, browseForSave function?
    The browseForOpen function takes a FileFilter. However when
    using browseForSave you can not set a fileFilter and the file
    extension has to be typed in manually. The File.extension property
    associated with the selected file is read-only. Does anyone know of
    a work around or anything that I could do to not enter the file
    Extension manually.

    For others if they would like to see:
    set audEXT to {"mp4", "m4a", "mp3", "aif", "aiff", "wav", "m4r"}
    property FoldersToMake : {"AUDIO", "VIDEOS", "Python workspace", "Documents", "PHOTOS", "Quartz Compositions", "Other"}
              tell application "Finder"
           repeat with newFolder in FoldersToMake
                                            try
                                                           make new folder of folder "CleanUP" with properties {name:"" & newFolder & ""}
                                            end try
                             end repeat
              end tell
              move (every file of desktop whose name extension is in audEXT) to the folder "AUDIO" of folder "Stuff"

  • Add attachment: File extension getting changed to lower case

    Hi
    When I upload the file say 'abc.TXT' the file extension gets changed to lowercase 'abc.txt' in the Unix server.
    I want the fileextension to be in Uppercase in the server also.
    file from desktop --- abc.TXT
    file on the server --- abc.txt
    Iam using delivered Addattachment functionality to upload the file to the server
    Peopletools 8.49
    Please advice.
    Edited by: 902509 on Dec 15, 2011 1:36 AM

    Just to help others who might be catching this off of search, here's a help link to PeopleBooks:
    http://docs.oracle.com/cd/E25688_01/pt852pbr0/eng/psbooks/tpcl/book.htm?File=tpcl/htm/tpcl02.htm#H4082

  • File Save dialog box not showing correct file name while saving file

    hi
    Currently, after the Submit button is hit, the File Save dialog box is displayed. If the user saves the file and then opens it then the output appears correct however if the user chooses to open the file without saving on the local machine then the correct viewer is not used to display the file. The name of the file is defaulted as qotSCopPrint.jsp and the default file viewer for jsp files is chosen to view the file. The format of the file is obviously not text (it is either pdf or rtf) so the output shows binary characters.

    data : v_repid like sy-repid.
    parameters : p_file like rlgrap-filename.
    initialization.
    v_repid = sy-repid.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'
           EXPORTING
                program_name  = v_repid
                dynpro_number = syst-dynnr
                field_name    = 'P_FILE'
           IMPORTING
                file_name     = p_file.
    Message was edited by:
            Chandrasekhar Jagarlamudi

  • Changing the default file name while saving the PDF interactive form

    Hi All,
    I am generating an Interactive PDF form using webdynpro, but when I try to save the PDF to my local machine the default file name comes as "<b>unknown.pdf</b>" so I have to manually go and enter the name before saving it.
    Is there any way to change this default name so that I don't have to manually edit the file name each time when I want to save the generated PDF interactive form?
    Please reply soon.
    Thanks in advance!

    I am running into the same issue. Setting the desname parameter (e.g. desname=temp.pdf) doesn't have any effect. Has anyone found a solution to this?
    Thanks,
    Brian

  • DW destroys file encoding while saving them

    hello there!
    I wanted to modifiy the latest wordpress file "wp-config-sample.php" by opening it and saving it without any changes and guess what; dreamweaver CS3 modifies the encoding of this file making un-usable to wordpress installation.
    I tried to open this file in notepad and save it in defferent encoding, and her's the results;
    save as --> ANSI --> works
    save as --> Unicode --> does not work
    save as --> Unicode Bg Endian--> does not work
    save as --> UTF --> works
    so at least saving in ANSI or UTF encoding works, but, in dreamweaver whatever I try it doesn't work, does that mean notepad is more advanced than DW!!
    the file "wp-config-sample.php" doesn't contain any header information, just some PHP variables to define.
    Dreamweaver CS 3 acts strange mayb when it doesn't find any header encoding information in the file.
    any help?
    NB: I checked the settings in the preferences and tried saving using the BOM segnitureand without it.. but always the same probleme

    Well, I discovered what was missing around with my code; the line break!
    if you go to Edit --> Preferences --> Code format --> you ahve to set line break type to CR LF (Windows).
    it was set to CR macintosh.
    have a nice day.

  • How to put current date in File name while saving PDF file.

    Hi expert,
    A report is scheduled for broadcasting  in PDF format . User wants it should have current date in its file name.
    Now system generated file name is Z_XXX_YYY_0000.pdf , but it should have Z_XXX_YYY_10012012.pdf or in any date format.
    Regards,
    Anand Mehrotra.

    First, how to best change the name of the folder. In Library view, there is a Folders panel within the lest hand side panel. If you select the folder and bring up the context menu, you can select the rename option to change the name/date of the folder. Lightroom will also cause the name to be changed on the HDD so both Lightroom as well as the OS will know about the change. This is the simplest way to handle folder name changes.
    Renaming the photos contained within the folder is a bit trickier. I have tried the Lightroom batch rename function, which should work by the way, I encountered some issues in which Lightroom wanted to substitute a sequence number, starting at 0001 rather than use the starting number I wanted to use. This was in Lightroom 4.x and I ended up having to manually rename files. To rename the files within the folder, select the folder to display the grid view of the images within that folder. Next, select all of the photos you want to rename and then select Library/Rename Photos (must be in Library mode) or just press the F2 key. This will open a Rename Photo dialog. Use the drop down box to select your naming scheme (or custom, which will open the Filename Template Editor where you can build your own template. From there, just click to confirm your choices and you should be able to rename your files.
    As I said above, I did have trouble with this in V4.x so I suggest only selecting one of the photos and testing it out. If it works, you can select the rest and complete your task. If it doesn't, then you can fix that, try again to get it to work or just manually rename your photos which is what I ended up doing.

  • How to add CSV file extension in output format of sap document in SCOT

    Hello All,
    i have added CSV in conversion rule through “SAP Customizing Implementation Guide–> SAPNetWeaver –>SAP Web Application Server -> Basis Services -> Communication Interfaces -> SAPconnect Client-Wide Settings -> General Settings -> Conversion Rules”. but it is not showing in SCOT (o/p format for SAP document).
    Please do needful

    i found this string on net
    add a Conversion-rule (transaction SCOT like this:
    CSV CSV 1 SX_OBJECT_CONVERT_TXT_INT
    How i Add .

  • How do I add jpg file extension?

    I recently exported some photos from iPhoto. Some of the photo thumbnail's have normal thumbnails and some only show up as white squares. I searched for these files and they look the same way in the iPhoto Original folder. The files that don't have a thumbnail are labelled as Plain Text and the ones with thumbnails are JPEG image.
    The good thing is that if I open the files, it opens as a picture, so they are okay. Is there any way I can change the file type so that I don't have this problem?
    Thanks in advance.

    You'll need a PC
    It looks like this may help
    http://www.mydigitallife.info/convert-microsoft-works-database-wdb-to-csv-or-exc el-without-works-installed/

  • Automatic MRP Run while saving SO

    Dear All,
       our customer requirement is when ever they make a sales order there should be an automatic MRP Run for all the materials available in Sales order.
    How to map this scenario.
    Useful answer will be definately awarded.
    Regards,
    HT

    Hi
    Firstly you plan what kind of planning you again do, whether : Make to stock or Make to order,
    If it is make to stock: then we have keep then a re-order point planning at MRP setting at material master and maintain mrp type as VV (Re-order planning). when ever the stock comes to re-order point stock, automatically MRP run takes place.
    If it is Make to order: then maintain the item category group as 0001 (Make to order planning) and after create Sales Order, we have do the MRP Run at MD02, and MD50.
    Reward if it helps
    Regards
    Prasanna R

Maybe you are looking for

  • To change the font of a selected row in a Jtable

    Hello, Is it possible to change the font of a selected row in a jtable? i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font? thank you.

  • Restriction in subtotal

    hi i have one report,there i am using oops-alv.here i am calculating subtotal,total on the basis of account nmber but for certain account we will not calulate total & subtotal,please help me,my program is                 T Y P E S   D E C L A R A T I

  • Core dump in _ti_mutex_unlock

    Greetings, I am using compiler (Sun C++ 5.5 2003/03/12 on a Sun/SunOS 5.8 system and I am getting the following traceback. Does anybody know what pacth I need to install to get around this issue? I though I had installed all the specified patches for

  • HT4436 does iCloud auto transfer pics from iPhone to macbookpro?

    I have IPhone and MacBook Pro.  I set up ICloud awhile back with assistance from Apple Genius.  All was well.  All pics taken on my IPhone was automatically transferring to my MacBook Pro...now they do not.  Please advise.

  • HRMS server sizing on NT

    Hi, We are planning to install HRMS on Windows NT server can someone suggest some server sizing tools and/or sites Thanks