Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ขั้นตอนสำคัญในการอ่าน/เขียนจาก/ไปยังการเชื่อมต่อ URL ใน java คืออะไร


URL คลาสของแพ็คเกจ java.net แสดงถึง Uniform Resource Locator ซึ่งใช้เพื่อชี้ทรัพยากร (ไฟล์หรือไดเร็กทอรีหรือข้อมูลอ้างอิง) ในเวิลด์ไวด์เว็บ

คลาสนี้จัดเตรียมคอนสตรัคเตอร์ที่หลากหลาย หนึ่งในนั้นยอมรับพารามิเตอร์ String และสร้างอ็อบเจ็กต์ของคลาส URL

openStream() เมธอดของคลาสนี้จะเปิดการเชื่อมต่อกับ URL ที่แสดงโดยอ็อบเจ็กต์ปัจจุบันและส่งคืนออบเจ็กต์ InputStream ซึ่งคุณสามารถอ่านข้อมูลจาก URL ได้

ดังนั้นหากต้องการอ่านข้อมูลจากหน้าเว็บ (โดยใช้คลาส URL) −

  • สร้างอินสแตนซ์คลาส java.net.URL โดยส่ง URL ของหน้าเว็บที่ต้องการเป็นพารามิเตอร์ไปยังตัวสร้าง

  • เรียกใช้เมธอด openStream() และดึงออบเจ็กต์ InputStream

  • สร้างอินสแตนซ์คลาส Scanner โดยส่งอ็อบเจ็กต์ InputStream ที่ดึงมาด้านบนเป็นพารามิเตอร์

ตัวอย่าง

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadingWebPage {
   public static void main(String args[]) throws IOException {
      //Instantiating the URL class
      URL url = new URL("https://www.something.com/");
      //Retrieving the contents of the specified page
      Scanner sc = new Scanner(url.openStream());
      //Instantiating the StringBuffer class to hold the result
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(sc.next());
         //System.out.println(sc.next());
      }
      //Retrieving the String from the String Buffer object
      String result = sb.toString();
      System.out.println(result);
      //Removing the HTML tags
      result = result.replaceAll("<[^>]*>", "");
      System.out.println("Contents of the web page: "+result);
   }
}

ผลลัพธ์

<html><body><h1>Itworks!</h1></body></html>
Contents of the web page: Itworks!