Search This Blog

Showing posts with label Files. Show all posts
Showing posts with label Files. Show all posts

How to Filter Filetypes using File Extensions in JFileChooser - Java File Chooser

how to filter files in Jfilechooser by file types or file formats using extensions in filename java codefile name file type filefilter file filter filtering files
Screenshot of following example java program
In java, to browse files or folders from the file system, we use the JFileChooser class. You can use  the JFileChooser object in two modes, save mode or open mode. Here we discuss about filtering file type by file extensions for opening the file. By default, the JFileChooser object will have an AcceptAllFileFilter. This file filter will allow the user to select file of any file type. The file filter will display text All files. If you want to restrict the file chooser to open only one type of file, you should first remove the AcceptAllFileFilter. To do this, call the following method:

myfilechooser.removeChoosableFileFilter(createoropenchooser.getAcceptAllFileFilter());


How to Easily Copy a File to Another File or Location in Java

The Files class in java has many useful static methods to copy and move files, create temporary files or folders etc. To copy a file from one location to another in Java, there is a static method copy in Files class. The Files class is in java.nio.file package. The method Files.copy() takes three arguments (parameters) : Path of source file (as object of Path class), Path of destination file ( as object of Path class ) and an option parameter. The option parameter can be one of the following:

StandardCopyOption.REPLACE_EXISTING
If the target file exists, then the target file is replaced.

StandardCopyOption.COPY_ATTRIBUTES
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes
that are copied is platform and file system dependent and therefore unspecified.

StandardCopyOption.NOFOLLOW_LINKS
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.

You have to import java.nio.file.StandardCopyOption to use option parameters.

try{
File sourcefile=new File("audio.mp3");
File destination=new File(System.getProperty("java.io.tmpdir")+"\\temp.mp3");
Files.copy(sourcefile.toPath(),destination.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException ex) {
ex.printStackTrace();
}

For the copy method, there are two other overloaded method definitions. In one, instead of source file's path, inputstream is the first parameter and the rest are same. For the other overloaded definition, an outputstream object is the second parameter instead of destination path object and the rest are same.

Similarly, to move a file from one location to another, there is a method move() in Files class. The parameters of this method is also same as those of copy method.