Java tutorial
/* * PortableMinecraftLauncher * Copyright (C) 2012 Jonas Kuemmerlin <rgcjonas@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.rgcjonas.portableMinecraftLauncher; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import org.apache.commons.io.FileUtils; /** * 'God Object' * manages program flow and computes our working directory. * @author Jonas Kuemmerlin <rgcjonas@gmail.com> * */ public class Main { /** * entry point * @param args */ public static void main(String[] args) { File workDir = getWorkingDirectory(); //ensure the working directory exists if (!workDir.exists()) { workDir.mkdir(); } File launcherJar = new File(workDir, "launcher.jar"); //download launcher if it doesn't exist if (!launcherJar.exists()) { try { URL launcherurl = new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar"); FileUtils.copyURLToFile(launcherurl, launcherJar); } catch (IOException e) { // shouldn't happen e.printStackTrace(); } } URL[] urls; try { urls = new URL[] { launcherJar.toURI().toURL() }; //this class loader mustn't be disposed while the launcher is running @SuppressWarnings("resource") LauncherClassLoader loader = new LauncherClassLoader(urls); //run it Class<?> launcherFrame = loader.loadClass("net.minecraft.LauncherFrame"); launcherFrame.getMethod("main", String[].class).invoke(null, (Object) args); } catch (Exception e) { // there's nothing we can do in that case but notify the dev e.printStackTrace(); } } /** * returns the working directory for the portable minecraft instance */ public static File getWorkingDirectory() { String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = null; try { decodedPath = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { //this is very unlikely to happen, we're just making eclipse happy e.printStackTrace(); } File ourDir = null; if (decodedPath.endsWith(".jar")) { //inside a jar file -> new dir named like the jar file ourDir = new File(decodedPath.substring(0, decodedPath.length() - 4)); } else { //subdir 'minecraft' ourDir = new File(decodedPath, "minecraft"); } //HACK: make it absolute here, since the other code requires File workDir = new File(ourDir.getAbsolutePath()); return workDir; } }