Save FileDialog in Java strips initial file extension

vocaro picture vocaro · Feb 28, 2011 · Viewed 11.3k times · Source

I'm using java.awt.FileDialog to create a dialog for saving a file. The problem is that when I specify a suggested (default) file name, FileDialog strips its extension. Example:

import java.awt.*;
import java.io.*;

public class SaveFile {
    public static void main(String[] args) {
        FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
        fileDialog.setFilenameFilter(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });
        fileDialog.setFile("Untitled.txt");
        fileDialog.setVisible(true);
        System.out.println("File: " + fileDialog.getFile());
    }
}

I would expect that when the FileDialog appears, the default file name is "Untitled.txt", but instead it is just "Untitled". When users click Save, I get back a filename without the extension. FileDialog does this on both Windows and OS X.

I don't get it. Why would FileDialog deliberately strip the extension? Is there some logical reason for this? The documentation doesn't discuss it. As a workaround, I could simply add the extension to the string that FileDialog returns, but still, this seems like a bug...

(Note that I cannot use JFileChooser; I need the native AWT FileDialog.)

Answer

Tom Quarendon picture Tom Quarendon · Feb 28, 2011

This doesn't happen for me, on Windows 7, with Sun Java 1.5 and 1.6.

The behaviour I get depends slightly on the setting of the "Hide extensions of known file types" in Windows explorer. If that's on, then the I don't see the extension in the file dialog, as you might expect, but it does return me the full file name.

EDIT: Realise I was wrong about AWT and native widgets -- confusing AWT and Swing.