- How to download and save a file from Internet in Java
- Save file window java
- Nested Class Summary
- Nested classes/interfaces declared in class java.awt.Dialog
- Nested classes/interfaces declared in class java.awt.Window
- Nested classes/interfaces declared in class java.awt.Container
- Nested classes/interfaces declared in class java.awt.Component
- Field Summary
- Fields declared in class java.awt.Dialog
- Fields declared in class java.awt.Component
- Fields declared in interface java.awt.image.ImageObserver
- Constructor Summary
- Method Summary
- Methods declared in class java.awt.Dialog
- Methods declared in class java.awt.Window
- Methods declared in class java.awt.Container
- Methods declared in class java.awt.Component
- Methods declared in class java.lang.Object
- Field Detail
- LOAD
- SAVE
- Constructor Detail
- FileDialog
- FileDialog
- FileDialog
- FileDialog
- FileDialog
- FileDialog
- Method Detail
- setTitle
- addNotify
- getMode
- setMode
- getDirectory
- setDirectory
- getFile
- getFiles
- setFile
- setMultipleMode
- isMultipleMode
- getFilenameFilter
- setFilenameFilter
- paramString
- Show save file dialog using JFileChooser
- Related Swing File Chooser Tutorials:
- Other Java Swing Tutorials:
- About the Author:
How to download and save a file from Internet in Java
In this article, we will look at different ways to download and save a file from the Internet in Java.
In Java 7+, the simplest and a pure Java-based solution is using the NIO API (classes in java.nio.* package) to download and save a file from a URL. Here is an example that downloads and saves an image from a URL to a file on the local file system:
try // internet URL URL url = new URL("https://i.imgur.com/mtbl1cr.jpg"); // download and save image ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream("cat.jpg"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); //close writers fos.close(); rbc.close(); > catch (IOException ex) ex.printStackTrace(); >
The transferFrom() method is by far more efficient than using a simple loop for copying bytes from the source channel to this channel. The third argument in transferFrom() is the maximum number of bytes to transfer. Long.MAX_VALUE will transfer at most 2^63 bytes.
Another JDK-only solution to download and save an Internet file is using the InputStream class. You can use File.openStream() to open an InputStream and then convert it into a file by using Files.copy() method:
try (InputStream in = URI.create("https://i.imgur.com/mtbl1cr.jpg") .toURL().openStream()) // download and save image Files.copy(in, Paths.get("cat.jpg")); > catch (IOException ex) ex.printStackTrace(); >
The Apache Commons IO library provides FileUtils.copyURLToFile() method to download and save a file from the Internet as shown below:
try // internet URL URL url = new URL("https://i.imgur.com/mtbl1cr.jpg"); // local file path File file = new File("cat.jpg"); // connection and read timeouts // TODO: adjust as per your own requirement int connectionTimeout = 10 * 1000; // 10 sec int readTimeout = 300 * 1000; // 3 min // download and save file FileUtils.copyURLToFile(url, file, connectionTimeout, readTimeout); > catch (IOException e) e.printStackTrace(); >
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>2.6version> dependency>
implementation 'commons-io:commons-io:2.6'
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
Save file window java
The FileDialog class displays a dialog window from which the user can select a file. Since it is a modal dialog, when the application calls its show method to display the dialog, it blocks the rest of the application until the user has chosen a file.
Nested Class Summary
Nested classes/interfaces declared in class java.awt.Dialog
Nested classes/interfaces declared in class java.awt.Window
Nested classes/interfaces declared in class java.awt.Container
Nested classes/interfaces declared in class java.awt.Component
Field Summary
This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.
This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.
Fields declared in class java.awt.Dialog
Fields declared in class java.awt.Component
Fields declared in interface java.awt.image.ImageObserver
Constructor Summary
Method Summary
Methods declared in class java.awt.Dialog
Methods declared in class java.awt.Window
Methods declared in class java.awt.Container
Methods declared in class java.awt.Component
Methods declared in class java.lang.Object
Field Detail
LOAD
public static final int LOAD
This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.
SAVE
public static final int SAVE
This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.
Constructor Detail
FileDialog
Creates a file dialog for loading a file. The title of the file dialog is initially empty. This is a convenience method for FileDialog(parent, «», LOAD) . Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
FileDialog
Creates a file dialog window with the specified title for loading a file. The files shown are those in the current directory. This is a convenience method for FileDialog(parent, title, LOAD) . Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
FileDialog
public FileDialog(Frame parent, String title, int mode)
Creates a file dialog window with the specified title for loading or saving a file. If the value of mode is LOAD , then the file dialog is finding a file to read, and the files shown are those in the current directory. If the value of mode is SAVE , the file dialog is finding a place to write a file. Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
FileDialog
Creates a file dialog for loading a file. The title of the file dialog is initially empty. This is a convenience method for FileDialog(parent, «», LOAD) . Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
FileDialog
Creates a file dialog window with the specified title for loading a file. The files shown are those in the current directory. This is a convenience method for FileDialog(parent, title, LOAD) . Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
FileDialog
public FileDialog(Dialog parent, String title, int mode)
Creates a file dialog window with the specified title for loading or saving a file. If the value of mode is LOAD , then the file dialog is finding a file to read, and the files shown are those in the current directory. If the value of mode is SAVE , the file dialog is finding a place to write a file. Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
Method Detail
setTitle
Sets the title of the Dialog. Note: Some platforms may not support showing the user-specified title in a file dialog. In this situation, either no title will be displayed in the file dialog’s title bar or, on some systems, the file dialog’s title bar will not be displayed.
addNotify
Creates the file dialog’s peer. The peer allows us to change the look of the file dialog without changing its functionality.
getMode
setMode
public void setMode(int mode)
Sets the mode of the file dialog. If mode is not a legal value, an exception will be thrown and mode will not be set.
getDirectory
setDirectory
Sets the directory of this file dialog window to be the specified directory. Specifying a null or an invalid directory implies an implementation-defined default. This default will not be realized, however, until the user has selected a file. Until this point, getDirectory() will return the value passed into this method. Specifying «» as the directory is exactly equivalent to specifying null as the directory.
getFile
Gets the selected file of this file dialog. If the user selected CANCEL , the returned file is null .
getFiles
Returns files that the user selects. If the user cancels the file dialog, then the method returns an empty array.
setFile
Sets the selected file for this file dialog window to be the specified file. This file becomes the default file if it is set before the file dialog window is first shown. When the dialog is shown, the specified file is selected. The kind of selection depends on the file existence, the dialog type, and the native platform. E.g., the file could be highlighted in the file list, or a file name editbox could be populated with the file name. This method accepts either a full file path, or a file name with an extension if used together with the setDirectory method. Specifying «» as the file is exactly equivalent to specifying null as the file.
setMultipleMode
public void setMultipleMode(boolean enable)
isMultipleMode
public boolean isMultipleMode()
getFilenameFilter
Determines this file dialog’s filename filter. A filename filter allows the user to specify which files appear in the file dialog window. Filename filters do not function in Sun’s reference implementation for Microsoft Windows.
setFilenameFilter
Sets the filename filter for this file dialog window to the specified filter. Filename filters do not function in Sun’s reference implementation for Microsoft Windows.
paramString
Returns a string representing the state of this FileDialog window. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null .
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Show save file dialog using JFileChooser
Swing provides class javax.swing.JFileChooser that can be used to present a dialog for user to choose a location and type a file name to be saved, using showSaveDialog() method. Syntax of this method is as follows:
public int showSaveDialog( Component parent)
where parent is the parent component of the dialog, such as a JFrame . Once the user typed a file name and select OK or Cancel, the method returns one of the following value:
-
- JFileChooser.CANCEL_OPTION : the user cancels file selection.
- JFileChooser.APPROVE_OPTION : the user accepts file selection.
- JFileChooser.ERROR_OPTION : if there’s an error or the user closes the dialog by clicking on X button.
After the dialog is dismissed and the user approved a selection, use the following methods to get the selected file:
Before calling showSaveDialog() method, you may want to set some options for the dialog:
-
- setDialogTitle ( String) sets a custom title text for the dialog.
- setCurrentDirectory ( File) sets the directory where will be saved.
Following is an example code:
// parent component of the dialog JFrame parentFrame = new JFrame(); JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(«Specify a file to save»); int userSelection = fileChooser.showSaveDialog(parentFrame); if (userSelection == JFileChooser.APPROVE_OPTION)
And following is a screenshot of the dialog:
You can download a fully working example code in the attachment section.
Related Swing File Chooser Tutorials:
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.