Cara Membaca File Dari Remote Server Di Java

Pada tutorial kali ini, kita akan belajar tentang Cara Membaca Sebuah File Dari Remote Server di Java. Untuk membaca file remote terutama dari protokol HTTP, Anda membutuhkan kelas java.net.URL dan java.net.URLConnection.

Contoh Program



Di bawah ini adalah contoh program Java untuk membaca sebuah file dari remote server:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class ReadFileFromRemoteDemo {
 public static void main(String[] args){
  String fileName = "http://yourdomain/file.txt";
  BufferedReader br = null;
  InputStreamReader is = null;
  try {
   URL url = new URL(fileName);
   
   URLConnection urlConnection = url.openConnection();
   
   is = new InputStreamReader(urlConnection.getInputStream());
   
   br = new BufferedReader(is);
   String data = "";
   while((data = br.readLine()) != null){
    System.out.println(data);
   }
  } catch (MalformedURLException e) {
   System.err.println("URL tidak ditemukan");
   e.printStackTrace();
  } catch (IOException e) {
   System.err.println("Tidak dapat mengakses file");
   e.printStackTrace();
  } finally{
    try {
     if(br != null){
      br.close();
     }
     
     if(is != null){
      is.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   
  }
  
 }
}


Output



Jika Anda compile dan jalankan program diatas, maka akan menampilkan output sebagai berikut:

Tidak dapat mengakses file
java.net.UnknownHostException: yourdomain
 at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
 at java.net.PlainSocketImpl.connect(Unknown Source)
 at java.net.SocksSocketImpl.connect(Unknown Source)
 at java.net.Socket.connect(Unknown Source)
 at java.net.Socket.connect(Unknown Source)
 at sun.net.NetworkClient.doConnect(Unknown Source)
 at sun.net.www.http.HttpClient.openServer(Unknown Source)
 at sun.net.www.http.HttpClient.openServer(Unknown Source)
 at sun.net.www.http.HttpClient.(Unknown Source)
 at sun.net.www.http.HttpClient.New(Unknown Source)
 at sun.net.www.http.HttpClient.New(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)


Share this

Related Posts

Previous
Next Post »