Created
June 11, 2019 06:32
-
-
Save ahmednasserpro/1c9f41f15c225c7a326a35f2325d6a0d to your computer and use it in GitHub Desktop.
(Retrieve files from Web) Write a Java program that retrieves a file from a Web server, as shown in Figure 17.32. The user interface includes a text field in which to enter the URL of the file name, a text area in which to show the file, and a button that can be used to submit an action. A label is added at the bottom of the applet to indicate t…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.event.*; | |
import java.io.IOException; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.util.Scanner; | |
import javax.swing.*; | |
public class URLTest extends JFrame { | |
JTextField field = new JTextField(40); | |
JButton view = new JButton("View"); | |
JTextArea area = new JTextArea(10, 0); | |
JLabel label = new JLabel(""); | |
URLTest() { | |
JScrollPane scroll = new JScrollPane(area); | |
JPanel p1 = new JPanel(new BorderLayout()); | |
p1.add(new JLabel("File name"), BorderLayout.WEST); | |
p1.add(field); | |
p1.add(view, BorderLayout.EAST); | |
JPanel p2 = new JPanel(new BorderLayout()); | |
p2.add(scroll); | |
label.setHorizontalAlignment(JLabel.LEFT); | |
p2.add(label, BorderLayout.SOUTH); | |
add(p1, BorderLayout.NORTH); | |
add(p2); | |
view.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
loadTextFromUrl(field.getText()); | |
} | |
}); | |
} | |
private String loadTextFromUrl(String stringUrl) { | |
StringBuilder builder = new StringBuilder(); | |
try { | |
URLConnection url = new URL(stringUrl).openConnection(); | |
url.setConnectTimeout(30000); | |
Scanner input = new Scanner(url.getInputStream()); | |
while (input.hasNext()) { | |
builder.append(input.nextLine()).append("\n"); | |
} | |
input.close(); | |
area.setText(builder.toString()); | |
label.setText("File loaded successfully"); | |
} catch (MalformedURLException ex) { | |
System.out.println(ex); | |
label.setText("File loaded failed"); | |
} catch (IOException ex) { | |
System.out.println(ex); | |
label.setText("File loaded failed"); | |
} | |
return builder.toString(); | |
} | |
public static void main(String[] args) { | |
JFrame frame = new URLTest(); | |
frame.pack(); | |
frame.setLocationRelativeTo(null); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.setVisible(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment