Java – Extract ZIP File

import  java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;

public class UnzipDemo {
    public static void main(String[] args) {
        String zipname = "data.zip";
        try {
            FileInputStream fis = new FileInputStream(zipname);
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
            ZipEntry entry;

            // Read each entry from the ZipInputStream until no more entry found
            while ((entry = zis.getNextEntry()) != null) {
                System.out.println("Unzipping: " + entry.getName());
                int size;
                byte[] buffer = new byte[2048];
                FileOutputStream fos = new FileOutputStream(entry.getName());
                BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);

                while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
            }
            zis.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java Servlet – Get User IP Address

import java.io.*;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Example Servlet to display user IP-address</title>");
        out.println("</head>");
        out.println("<body>");

        //Print out the IP address of the caller
        out.println(request.getRemoteAddr());

        out.println("</body>");
        out.println("</html>");
        out.close();
    }
}

Java – Find Hostname of Local Machine

import java.net.*;

class myName {

  public static void main (String args[]) {

    try {
      InetAddress address = InetAddress.getLocalHost();
      System.out.println("Hello. My name is " +  address.getHostName());
    }
    catch (UnknownHostException e) {
      System.out.println("I'm sorry. I don't know my own name.");
    }

  }

}

Page 1 of 812345...Last »