简体   繁体   中英

How do I Execute Java from Java?

I have this DownloadFile.java and downloads the file as it should:

import java.io.*;
import java.net.URL;

public class DownloadFile {    
    public static void main(String[] args) throws IOException {
        String fileName = "setup.exe";
            // The file that will be saved on your computer
        URL link = new URL("http://onlinebackup.elgiganten.se/software/elgiganten/setup.exe");
            // The file that you want to download

        // Code to download
        InputStream in = new BufferedInputStream(link.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();

        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(response);
        fos.close();
        // End download code

        System.out.println("Finished");
    }
}

I want to execute this from a mouse event in Gui.java .

private void jLabel17MouseClicked(java.awt.event.MouseEvent evt){

}   

How do I do this?

Your current method is a static method, which is fine, but all the data that it extracts is held tightly within the main method, preventing other classes from using it, but fortunately this can be corrected.

My suggestion:

  • re-write your DownloadFile code so that it is does not simply a static main method, but rather a method that can be called by other classes easily, and that returns the data from the file of interest. This way outside classes can call the method and then receive the data that the method extracted.
  • Give it a String parameter that will allow the calling code to pass in the URL address.
  • Give it a File parameter for the file that it should write data to.
  • Consider having it return data (a byte array?), if this data will be needed by the calling program.
  • Or if it does not need to return data, perhaps it could return boolean to indicate if the download was successful or not.
  • Make sure that your method throws all exceptions (such as IO and URL excptions) that it needs to throw.
  • Also, if this is to be called by a Swing GUI, be sure to call this type of code in a background thread, such as in a SwingWorker, so that this code does not tie up the Swing event thread, rendering your GUI frozen for a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM