Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.Scanner;
- /**
- * A simple program that finds information from a website
- * of your choosing and saves it to a file of your choosing
- */
- public class PaulIsDumb {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Ask and Receive URL input
- System.out.println("Please input a URL:");
- String url = scanner.nextLine();
- // Detect if valid url
- if(!url.startsWith("http") || !url.contains("//")) {
- System.out.println("Invalid URL.");
- return;
- }
- // Ask and Receive file name
- System.out.println("Please input a file name:");
- String fileName = scanner.nextLine();
- // Retrieve information from the website
- String retrieved;
- try { retrieved = makeGETRequest(url);
- } catch(IOException ex) {
- System.out.println("There was an error whilst attempting to complete your request.");
- return;
- }
- // Write to file
- try { writeToFile(new File(fileName), retrieved);
- } catch(IOException ex) {
- System.out.println("There was an error whilst attempting to write to the file.");
- return;
- }
- // Tell user the operation has concluded
- System.out.println("Successfully written to file.");
- }
- /**
- * Writes a string to a file
- *
- * @param file File to write to
- * @param meta Information to write
- */
- private static void writeToFile(File file, String meta) throws IOException {
- FileWriter writer = new FileWriter(file);
- writer.write(meta);
- writer.close();
- }
- /**
- * Makes a GET request to a specific URL
- *
- * @param url Website Address
- * @return Response
- */
- private static String makeGETRequest(String url) throws IOException {
- URL obj = new URL(url);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setRequestProperty("User-Agent", "Mozilla/5.0");
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- StringBuilder response = new StringBuilder();
- while ((inputLine = in.readLine()) != null) response.append(inputLine).append("\n");
- in.close();
- return response.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement