- Tham gia
- 21/02/2018
- Bài viết
- 667
Class để Update plugin tự động
Mã:
import java.io.*;
public void onEnable() {
if(Updater.check(this.getDescription().getVersion())) {
Bukkit.log("A new version detected v" + Updater.ver());
if(!this.getFile().delete()) Bukkit.log("An error occured while removing old version");
Updater.update(new File("./plugins/MyPlugin-" + Updater.ver() + ".jar"));
Bukkit.log("Update completed");
}
}
Mã:
ver$1.0.0
url$http://my.domain.org/plugin.jar
Mã:
package acayrin.updater;
import java.io.*;
import java.net.*;
public class Updater {
protected static String toGET = "http://my.domain.org/plugin.txt";
public static boolean check(String ver) {
String chk = ver();
if(ver.equals(chk)) return false;
return true;
}
public static void update(File file) {
try {
URL link = new URL(url());
InputStream input = link.openStream();
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' is a directory");
if (!file.canWrite())
throw new IOException("File '" + file + "' cannot be written");
} else {
File parent = file.getParentFile();
if ((parent != null) && (!parent.exists()) && (!parent.mkdirs())) {
throw new IOException("File '" + file + "' could not be created");
}
}
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
input.close();
output.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static String ver() {
String ver = null;
try {
URL url = new URL(toGET);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("ver")) ver = line.replace("ver$", "");
}
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ver;
}
public static String url() {
String res = null;
try {
URL url = new URL(toGET);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("url")) res = line.replace("url$", "");
}
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}







