NoClassDefError when using classes from a .jar - java

I am attempting to use classes from a .jar file in a my .java file Tweetauthent. The .jar file is in another directory. I make a request to the Twitter rest api to obtain a bearertoken. Tweetauthent compiles when I run
-javac -cp /path/to/jar Tweetauthent.java
This is the code
import java.io.BufferedReader;
import java.lang.StringBuilder;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
public class Tweetauthent{
static String consumerkey = "astring";
static String consumersecret = "astring";
static String endurl = "https://api.twitter.com/oauth2/token";
public static void main(String []args){
Tweetauthent t = new Tweetauthent();
try{
System.out.println(t.requestBearerToken(endurl));
}catch(IOException e){
System.out.println(e);
}
}
public static String encodeKeys(String consumerKey,String consumerSecret){
try{
String encodedConsumerKey = URLEncoder.encode(consumerKey,"UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret,"UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.getEncoder().encode(fullKey.getBytes());
return new String(encodedBytes);
}catch(UnsupportedEncodingException e){
return new String();
}
}
public static String requestBearerToken(String endPointURL) throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys("<consumerkey>","<consumersecret>");
try{
URL url = new URL(endPointURL);
connection = (HttpsURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Host","api.twitter.com");
connection.setRequestProperty("User-Agent","TweetPersonalityAnalyzer");
connection.setRequestProperty("Authorization","Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length","29");
writeRequest(connection, "grant_type=client_credentials");
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));
if(obj != null){
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
return ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
return new String();
}catch(MalformedURLException e){
throw new IOException("Invalid endpoint URL specified.", e);
}
finally{
if( connection != null){
connection.disconnect();
}
}
}
public static boolean writeRequest(HttpsURLConnection connection, String textBody){
try{
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch(IOException e){
return false;
}
}
public static String readResponse(HttpsURLConnection connection){
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null){
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}catch(IOException e){
return new String();
}
}
The error I get when I run
java Tweetauthent
is
java.lang.NoClassDefFoundError: org/json/simple/JSONValue
at Tweetauthent.requestBearerToken(Tweetauthent.java:61)
at Tweetauthent.main(Tweetauthent.java:27)
Caused by: java.lang.ClassNotFoundException:
org.json.simple.JSONValue
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
From what I understand the NoClassDefFoundError is thrown when the JVM cant find neccesary class files that the .java file used to compile. What would be causing this? Is there a way to add the path of the jar too -java? Oh and with expected consumerkey and secret strings.
UPDATE: when I add the classpath to java
java /path/to/jar Tweethauthent
I get Error: could not find or load main class Tweetauthent
Any help would be greatly appreciated thank you!

You have a run time class path issue.
I don't see how you've set the runtime classpath. The fact that you compiled is necessary, but insufficient.
Either you don't have the runtime classpath set properly or the JAR is not part of your package.

You need to reference the runtime dependencies in -classpath or -cp option of the java command:
java -classpath /path/to/jar Tweetauthent
If you want to run with arguments add them as parameter after the Java file:
java -classpath /path/to/jar Tweetauthent <consumerkey> <consumersecret>

Related

Statically Loading a .txt File

I understand that this question has been asked often before, and yet none of the other answers have worked for me. I am trying to statically load a .txt file in. It works wile inside the compiler (Eclipse) but after I export I get a FileNotFound exception.
I need a method that will take in a file path and load that .txt file statically, and return that file as a String. I think I have to do something with loadRecourceAsStream() but I am not sure.
Here is how I am loading it now:
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
Here are some other things I have tried. They all work in the compiler but not after exporting:
public static String loadFileAsString(String path){
StringBuilder builder = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine()) != null)
builder.append(line + "\n");
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
br.close();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
And:
public static String getFile(String path) {
Scanner controlBoard = new Scanner(System.in);
controlBoard = new Scanner(Utils.class.getResourceAsStream(path));
String file = controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
return file;
}
And:
public static String getFile(String path) {
System.out.println("test");
StringBuilder out = new StringBuilder();
try {
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null) {
out.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return out.toString();
}
Any ideas on what I should do?
I think your problem has to be related in how you are running your program when exported as I have taken your code, created a jar, run it and it worked without changing a single line. Well, I have added a main function to be able to run it. I add the code just in case but you will see that the code is the same.
package com.iseji.app.main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main (String args[]){
System.out.println(getFilePath(args[0]));
}
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
}
So the question is how have you imported the file into a jar. You can really just use the "Export to" functionality of your IDE (Eclipse, IntelliJ or whatever). On the other hand I recommend you to use a life-cycle software framework like maven or gradle. Just as an example I show the gradle file that I use to create the jar (but as I say, this is not really important)
apply plugin: 'java'
sourceCompatibility = 1.5
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
jar {
manifest {
attributes 'Main-Class': 'com.iseji.app.main.Main'
}
}
Anyway how you export your code to a jar, the key is how the Manifest file looks like. You have to be sure that it indicates which is the main class. Verify that it is similar to:
Manifest-Version: 1.0
Main-Class: com.iseji.app.main.Main
In such a way you will be able to run it as normally passing as a parameter the file to read
java -jar ReadingFile-1.0.jar ../../src/main/resources/sample.txt
As I said at the beginning your code is fine. Just double check how you are exporting the code and running it

Java: ConnectException/Cannot find or load Main-Class

So in a nutshell, I'm just trying to get a small working skeleton program that I can use to sort of learn about Http communication and "feel" my way around to figure out what I will eventually need for a bigger program I am working on. This particular code here is actually just a chopped up version of an example from the Apache libraries. I could compile the examples listed on the Apache website, but they didn't run properly, giving a "java.net.ConnectException". I figured it had to do with Windows c-blocking a program like this from making a connection, and that I would need to run it as an administrator. I then tried taking the code and throwing it into an executable jar file, but I get a Cannot-find-or-load-main-class error. Am I an idiot or is the Apache library a little outdated/not fit for Win 8/something else?
Code below:
package NewProject;
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
class NewProject
{
public static void main(String[] args) throws Exception
{
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost host = new HttpHost("localhost", 8080);
coreContext.setTargetHost(host);
Out os = new Out("TestOut.txt");
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
try
{
String[] targets =
{
"http://www.google.com/"
};
for (int i = 0; i < targets.length; i++)
{
if (!conn.isOpen())
{
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
os.println(">> Request URI: " + request.getRequestLine().getUri());
httpexecutor.preProcess(request, httpproc, coreContext);
HttpResponse response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);
os.println("<< Response: " + response.getStatusLine());
os.println(EntityUtils.toString(response.getEntity()));
os.println("==============");
if (!connStrategy.keepAlive(response, coreContext))
{
conn.close();
}
else
{
os.println("Connection kept alive...");
}
}
}
catch (IndexOutOfBoundsException iob)
{
os.println("What happened here?");
}
finally
{
conn.close();
}
return;
}
}
... they didn't run properly, giving a "java.net.ConnectException"
That could be caused by lots of things. There are clues in the exception message ... which you chose not to share with us.
... "Cannot find or load Main-Class"
Again multiple possible causes, and there are clues in the exception message ... which you chose not to share with us.
But the fact that you have created a JAR file plus the "Main-Class" hint in the error message fragment you provided suggest that you made a mistake in the creation of the JAR file; i.e. you used the wrong name for the "Main-Class" attribute.
Given that source code, the "Main-Class" attribute should be "NewProject.NewProject". I suspect you set it to something else.
A second possibility is that you haven't handled the dependency on the Apache library correctly. The Apache classes need to be on the classpath specified by the JAR file. (You can't use a -cp argument or $CLASSPATH when you launch with java -jar.)
Am I an idiot or is the Apache library a little outdated/not fit for Win 8/something else?
There is nothing wrong with the Apache library.
The code you posted seems a little low level (e.g. interacting directly with Socket connections). The code posted below should give you what it sounds like you are looking for. The classes used also give you a lot of inroads into setting and getting http parameters (e.g. headers, time-outs, etc).
package org.yaorma.example.http.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
String response;
response = get("http://www.google.com");
System.out.println("RESPONSE FROM GET -----------------------------------------");
System.out.println(response);
response = post("http://httpbin.org/post", "This is the message I posted to httpbin.org/post");
System.out.println("RESPONSE FROM POST -----------------------------------------");
System.out.println(response);
}
/**
* Method to post a request to a given URL.
*/
public static String post(String urlString, String message) {
try {
// get a connection
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// set the parameters
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// send the message
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(message);
writer.flush();
writer.close();
os.close();
// get the response
conn.connect();
InputStream content = (InputStream) conn.getInputStream();
// read the response
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String rtn = "";
String line;
while ((line = in.readLine()) != null) {
rtn += line + "\n";
}
return rtn;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
/**
* Method to do a get from a given URL.
*/
public static String get(String urlString) {
try {
// get a connection
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// set the parameters
conn.setRequestMethod("GET");
conn.setDoOutput(true);
// get the response
conn.connect();
InputStream content = (InputStream) conn.getInputStream();
// read the response
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String rtn = "";
String line;
while ((line = in.readLine()) != null) {
rtn += line + "\n";
}
return rtn;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}

SocketException: Connection reset

I all but copied the following code from here. I get a java.net.SocketException on line 10 saying "Connection Reset".
import java.net.*;
import java.io.*;
import org.apache.commons.io.*;
public class HelloWorld {
public static void main(String[] x) {
try {
URL url = new URL("http://money.cnn.com/2013/06/07/technology/security/page-zuckerberg-spying/index.html");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.print(body);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm worried this may not actually be an issue with the actual code but rather some permission I need to give Java. Is there something wrong with my code or is this an environment issue?
I used your code with small modification cause I don't have IOUtils at hands. And it works as it should. There is no need to set agent. No special privileges also as I run it by normal user.
try {
URL url = new URL("http://money.cnn.com/2013/06/07/technology/security/page-zuckerberg-spying/index.html");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
System.out.print(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}

Java: Accessing a File from an FTP Server

So I have this FTP server with a bunch of folders and files inside.
My program needs to access this server, read all of the files, and display their data.
For development purposes I've been working with the files on my hard drive, right in the "src" folder.
But now that the server is up and running, I need to connect the software to it.
Basically what I want to do is get a list of the Files in a particular folder on the server.
This is what I have so far:
URL url = null;
File folder = null;
try {
url = new URL ("ftp://username:password#www.superland.example/server");
folder = new File (url.toURI());
} catch (Exception e) {
e.printStackTrace();
}
data = Arrays.asList(folder.listFiles(new FileFilter () {
public boolean accept(File file) {
return file.isDirectory();
}
}));
But I get the error "URI scheme is not 'file'."
I understand this is because my URL starts with "ftp://" and not "file:"
However I can't seem to figure out what I'm supposed to do about it!
Maybe there's a better way to go about this?
File objects cannot handle an FTP connection, you need to use a URLConnection:
URL url = new URL ("ftp://username:password#www.superland.example/server");
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream();
...
Consider as an alternative FTPClient from Apache Commons Net which has support for many protocols. Here is an FTP list files example.
if you use URI with file you can use your code but , but when you want to use ftp so you need to this kind of code; code list the name of the files under your ftp server
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL url = new URL("ftp://username:password#www.superland.example/server");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
EDITED Demo Code Belongs to Codejava
package net.codejava.ftp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class FtpUrlListing {
public static void main(String[] args) {
String ftpUrl = "ftp://%s:%s#%s/%s;type=d";
String host = "www.myserver.com";
String user = "tom";
String pass = "secret";
String dirPath = "/projects/java";
ftpUrl = String.format(ftpUrl, user, pass, host, dirPath);
System.out.println("URL: " + ftpUrl);
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
System.out.println("--- START ---");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("--- END ---");
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Store minecraft data in current directory

EDIT: used different decompiler now includes the Util$OS.class file
I am trying to modify the mine craft launcher to check for a minecraft folder in the current working directory and if none exists then use the established routines to Crete and download the needed files. This is my first foray into java programing so I am feeling a bit lost. Here is the source of the offending class file: (the block that i think needs modifying starts on line 15)
File Util.class
package net.minecraft;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.security.PublicKey;
import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
public class Util
{
private static File workDir = null;
public static File getWorkingDirectory() {
if (workDir == null) workDir = getWorkingDirectory("minecraft");
return workDir;
}
public static File getWorkingDirectory(String applicationName) {
String userHome = System.getProperty("user.home", ".");
File workingDirectory;
File workingDirectory;
File workingDirectory;
File workingDirectory;
switch ($SWITCH_TABLE$net$minecraft$Util$OS()[getPlatform().ordinal()]) {
case 1:
case 2:
workingDirectory = new File(userHome, '.' + applicationName + '/');
break;
case 3:
String applicationData = System.getenv("APPDATA");
File workingDirectory;
if (applicationData != null) workingDirectory = new File(applicationData, "." + applicationName + '/'); else
workingDirectory = new File(userHome, '.' + applicationName + '/');
break;
case 4:
workingDirectory = new File(userHome, "Library/Application Support/" + applicationName);
break;
default:
workingDirectory = new File(userHome, applicationName + '/');
}
if ((!workingDirectory.exists()) && (!workingDirectory.mkdirs())) throw new RuntimeException("The working directory could not be created: " + workingDirectory);
return workingDirectory;
}
private static OS getPlatform() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) return OS.windows;
if (osName.contains("mac")) return OS.macos;
if (osName.contains("solaris")) return OS.solaris;
if (osName.contains("sunos")) return OS.solaris;
if (osName.contains("linux")) return OS.linux;
if (osName.contains("unix")) return OS.linux;
return OS.unknown;
}
public static String excutePost(String targetURL, String urlParameters)
{
HttpsURLConnection connection = null;
try
{
URL url = new URL(targetURL);
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
Certificate[] certs = connection.getServerCertificates();
byte[] bytes = new byte[294];
DataInputStream dis = new DataInputStream(Util.class.getResourceAsStream("minecraft.key"));
dis.readFully(bytes);
dis.close();
Certificate c = certs[0];
PublicKey pk = c.getPublicKey();
byte[] data = pk.getEncoded();
for (int i = 0; i < data.length; i++) {
if (data[i] == bytes[i]) continue; throw new RuntimeException("Public key mismatch");
}
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
{
String line;
response.append(line);
response.append('\r');
}
rd.close();
String str1 = response.toString();
return str1;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
if (connection != null)
connection.disconnect();
}
throw localObject;
}
public static boolean isEmpty(String str) {
return (str == null) || (str.length() == 0);
}
public static void openLink(URI uri) {
try {
Object o = Class.forName("java.awt.Desktop").getMethod("getDesktop", new Class[0]).invoke(null, new Object[0]);
o.getClass().getMethod("browse", new Class[] { URI.class }).invoke(o, new Object[] { uri });
} catch (Throwable e) {
System.out.println("Failed to open link " + uri.toString());
}
}
private static enum OS
{
linux, solaris, windows, macos, unknown;
}
}
I have done some research on getting the current working directory but i am not sure what needs modifing. If someone could at least explain what the various parts of the file mean that would be very helpful.
public static File getWorkingDirectory(String applicationName) {
File workingDirectory = new File("." + File.separator + applicationName);
if ((!workingDirectory.exists()) && (!workingDirectory.mkdirs()))
throw new RuntimeException("The working directory could not be created: " + workingDirectory);
return workingDirectory;
}
Sorry for the confusion, this should work just fine for you.
It will create a minecraft folder in the same directory as your launcher.
Note: On OS X this will still create the folder in the folder as the .app, not the .app/Contents/Resources/Java folder that the actual JAR is in, so you wont have any problem on any operating system.
Hope this helps!
I'm still not completely sure I understand your goals.
If you want to have it download "Minecraft" for you I'd try to do it in a batch file and shell script and just run the one that was appropriate for your system.
If you want to somehow "download" your worlds, texture packs and mods from somewhere then you could do the same.
If what you want is for every minecraft install you are playing on to use your data (like on a USB stick or something) you might have batch files that either copy over the data before running minecraft or perhaps use "ln" to replace the directories that minecraft thinks it's going to use with your own on your usb stick.
You can always modify the field that points to the directory where MC puts its saves and change it to whatever you want. Here's a snippet from my launcher (http://www.github.com/lekro/ModdishLauncher):
ClassLoader cl = new URLClassLoader(urls, ModdishLauncher.class.getClassLoader());
Class<?> mc = null;
try {
mc = cl.loadClass("net.minecraft.client.Minecraft");
} catch (ClassNotFoundException e2) {
System.err.println("Couldn't find Minecraft main class!");
e2.printStackTrace();
}
Field[] fields = mc.getDeclaredFields();
Field mcPathField = null;
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
if (f.getType() != File.class) {
continue;
}
if (f.getModifiers() != (Modifier.PRIVATE + Modifier.STATIC)) {
continue;
}
mcPathField = f;
break;
}
mcPathField.setAccessible(true);
try {
mcPathField.set(null, new File(myDir + "/minecrafts/"+minecraftType+"/"));
} catch (IllegalArgumentException e2) {
e2.printStackTrace();
} catch (IllegalAccessException e2) {
e2.printStackTrace();
}
This takes the hardcoded path field inside the Minecraft class and modifies it to whatever you want it to be. (e.g. on a USB stick, in a custom folder, etc.)

Categories