Caranya adalah kita memanfaatkan argumen pada saat menjalankan program.
Berikut ini adalah tahapan pembuatan program.
- Buat project baru dengan nama "downloadURL2WithArguments". Caranya sama seperti artikel sebelumnya.
- Sesuaikan kode program seperti dibawah ini.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package downloadurl2witharguments; import java.io.*; import java.net.*; /** * * @author it916 */ public class DownloadURL2WithArguments { /** * @param args the command line arguments */ public static void saveFile(URL url, String file) throws IOException { System.out.println("opening connection"); InputStream in = url.openStream(); FileOutputStream fos = new FileOutputStream(new File(file)); System.out.println("reading file..."); int length = -1; byte[] buffer = new byte[1024];// buffer for portion of data from // connection while ((length = in.read(buffer)) > -1) { fos.write(buffer, 0, length); } fos.close(); in.close(); System.out.println("file was downloaded"); } public static void main(String[] args) { // TODO code application logic here try { //URL url = new URL("http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip"); URL url = new URL(args[0]); //Sesuaikan baris ini dengan struktur folder anda dan nama file yang anda kehendaki //String fileName = "/home/it916/Desktop/javaDownloadUrl-ntradping.zip"; String fileName = args[1]; saveFile(url,fileName); } catch(IOException e) { e.printStackTrace(); } } }
- Kompilasi program seperti petunjuk dalam artikel sebelumnya ("Run -> Clean and Build Project (downloadURL2WithArguments)").
- Jalankan program melalui terminal dengan format :
java -jar "alamat url download file" "lokasi penyimpanan file"
- Berikut ini contoh hasilnya.
it916@planning-ho-pc:~/NetBeansProjects$ java -jar downloadURL2WithArguments/dist/downloadURL2WithArguments.jar "http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip" "/home/it916/Desktop/download234.zip" opening connection reading file... file was downloaded it916@planning-ho-pc:~/NetBeansProjects$ ls -l /home/it916/Desktop/ | grep download234 -rw-rw-r-- 1 it916 it916 71251 Oct 17 05:04 download234.zip
Tidak ada komentar:
Posting Komentar