61FIT3NPR - W03 Tut Java Streams
61FIT3NPR - W03 Tut Java Streams
HANOI UNIVERSITY
import java.io.*;
import java.net.*;
package tut3;
import java.io.*;
import java.net.*;
import java.util.*;
(Downloads the file, and also prints the file to the console,
and prints the number of occurrences of each kind of
character in the file.)
package tut3;
import java.io.*;
import java.net.*;
import java.util.*;
// Reads from URL and prints file contents and tally of each char.
public void download(String targetFileName) throws IOException {
super.download(targetFileName);
package tut3;
import java.io.*;
import java.net.*;
import java.util.*;
package tut3.javaio.stream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
OutputStream os = new
FileOutputStream("./Test/test_writerOutputStream.txt");
byte[] by = new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 31, 34,
92, 10 }; //10 = "\n" new line , 31 = control code chart , 34 = """ , 92 =
"\"
byte[] by2 = new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 'b', 'o',
'y' };
os.write(by);
os.flush();
os.write(by2);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Another: https://www.codejava.net/java-se/networking/use-
httpurlconnection-to-download-file-from-an-http-url
The following class diagram illustrates how the application will be designed:
o HTTPDownloadUtil: encapsulates the core functionality of the application -
download file from an HTTP URL. This class is implemented based on the
tutorial Use HttpURLConnection to download file from an HTTP URL, but is
modified to work with updating download progress while the file is being
transferred.
o DownloadTask: executes thread the file download in a background rather in
the Swing’s event dispatcher thread (EDT), so the GUI will not become
unresponsive when the download is taking place.
o SwingFileDownloadHTTP: is the main application which displays the GUI that
allows users to enter a download URL, choose a location to save the file,
and start downloading.
o JFilePicker and FileTypeFilter: These components are used by
the SwingFileDownloadHTTP class to show a file chooser. These classes are
taken from the article File picker component in Swing.
Let’s see how these classes are implemented in details.
package net.codejava.swing.download;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A utility that downloads a file from a URL.
*
* @author www.codejava.net
*
*/
public class HTTPDownloadUtil {
/**
* hold input stream of HttpURLConnection
*/
private InputStream inputStream;
/**
* Downloads a file from a URL
*
* @param fileURL
* HTTP URL of the file to be downloaded
* @throws IOException
*/
public void downloadFile(String fileURL) throws IOException {
URL url = new URL(fileURL);
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
} else {
throw new IOException(
"No file to download. Server replied HTTP code: "
+ responseCode);
}
}
This utility class does not actually download the file. It only makes a connection,
parses HTTP headers to get file information, and opens the connection’s input
stream which will be used by the DownloadTask class.
2. Code of the DownloadTask class
package net.codejava.swing.download;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
/**
* Execute file download in a background thread and update the progress.
* @author www.codejava.net
*
*/
public class DownloadTask extends SwingWorker<Void, Void> {
private static final int BUFFER_SIZE = 4096;
private String downloadURL;
private String saveDirectory;
private SwingFileDownloadHTTP gui;
/**
* Executed in background thread
*/
@Override
protected Void doInBackground() throws Exception {
try {
HTTPDownloadUtil util = new HTTPDownloadUtil();
util.downloadFile(downloadURL);
setProgress(percentCompleted);
}
outputStream.close();
util.disconnect();
} catch (IOException ex) {
JOptionPane.showMessageDialog(gui, "Error downloading file: " +
ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
setProgress(0);
cancel(true);
}
return null;
}
/**
* Executed in Swing's event dispatching thread
*/
@Override
protected void done() {
if (!isCancelled()) {
JOptionPane.showMessageDialog(gui,
"File has been downloaded successfully!", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import net.codejava.swing.JFilePicker;
/**
* A Swing application that downloads file from an HTTP server.
* @author www.codejava.net
*
*/
public class SwingFileDownloadHTTP extends JFrame implements
PropertyChangeListener {
private JLabel labelURL = new JLabel("Download URL: ");
private JTextField fieldURL = new JTextField(30);
public SwingFileDownloadHTTP() {
super("Swing File Download from HTTP server");
// set up layout
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(5, 5, 5, 5);
// set up components
filePicker.setMode(JFilePicker.MODE_SAVE);
filePicker.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTOR
IES_ONLY);
buttonDownload.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
buttonDownloadActionPerformed(event);
}
});
fieldFileName.setEditable(false);
fieldFileSize.setEditable(false);
constraints.gridx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 1.0;
add(fieldURL, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 0.0;
constraints.gridwidth = 2;
constraints.fill = GridBagConstraints.NONE;
add(filePicker, constraints);
constraints.gridy = 2;
constraints.anchor = GridBagConstraints.CENTER;
add(buttonDownload, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.WEST;
add(labelFileName, constraints);
constraints.gridx = 1;
add(fieldFileName, constraints);
constraints.gridy = 4;
constraints.gridx = 0;
add(labelFileSize, constraints);
constraints.gridx = 1;
add(fieldFileSize, constraints);
constraints.gridx = 0;
constraints.gridy = 5;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.WEST;
add(labelProgress, constraints);
constraints.gridx = 1;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
add(progressBar, constraints);
pack();
setLocationRelativeTo(null); // center on screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* handle click event of the Upload button
*/
private void buttonDownloadActionPerformed(ActionEvent event) {
String downloadURL = fieldURL.getText();
String saveDir = filePicker.getSelectedFilePath();
if (saveDir.equals("")) {
JOptionPane.showMessageDialog(this,
"Please choose a directory save file!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
progressBar.setValue(0);
/**
* Update the progress bar's state whenever the progress of download
changes.
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("progress")) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
}
}
/**
* Launch the application
*/
public static void main(String[] args) {
try {
// set look and feel to system dependent
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
);
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingFileDownloadHTTP().setVisible(true);
}
});
}
}
This builds the user interface for the application and wires all the pieces together to
form a complete application. To update the progress bar while the download is
taking place, it “listens” to the property named “progress” which is repeatedly
updated by the DownloadTask class.
4. Testing the application
To test this application, we need to have a downloadable URL, for example:
http://www.us.apache.org/dist/struts/source/struts-2.3.12-src.zip
Run the application and type the above URL into the Download URL field:
Click Browse… button to select a directory where the file will be stored, for
example: E:\Download, and hit Download button to start downloading the file. Just a
second you will see the file information is updated in the fields File name and File
size, as well as the progress bar gets updated quickly:
To experiment yourself with this nice application, download full source code and
executable jar file of in the attachments section. You can also clone the sample
project on GitHub.
https://downloads.apache.org/struts/2.5.33/struts-2.5.33-all.zip
https://www.codejava.net/coding/swing-application-to-download-files-from-http-
server-with-progress-bar
(package net.codejava.swing;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
buttonActionPerformed(evt);
}
});
add(label);
add(textField);
add(button);
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
} else if (mode == MODE_SAVE) {
if (fileChooser.showSaveDialog(this) ==
JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}