再次问好stackoverflow,今天我正在为我的Minecraft服务器编写文件阅读器。我们通过文件使用了一种bank-fino存储。由于我们已经更改为mysql,因此我需要读取一个和一个文件以获取用户的数量。这是读者代码:
主档案:
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class BankReader {
/**
* @param args
*/
public static void main(String[] args) {
if(args.length == 0){
System.out.println("\n" +
"\n" +
" Mangler parameters.\n" +
" Usage: buildnorgebankreader [username]" +
"\n" +
"");
} else {
// Find file
File f = new File("C:"+File.separator+"users"+File.separator
+"Hultberg"+File.separator+"Documents"+File.separator
+"E fra laptop"+File.separator+"bukkit"+File.separator
+"testserver"+File.separator+"bank", args[0]);
if(!f.exists()){
System.out.println("\n" +
"\n" +
" fant ikke brukeren '"+args[0]+"' sin bank fil\n" +
"\n" +
"");
} else {
// Try read
try {
BankData bank = (BankData)load(f);
System.out.println("På konto: "+bank.getBankAmount());
} catch (Exception e) {
System.out.println("\n" +
"\n" +
" kunne ikke lese brukeren '"+args[0]+"' sin bank fil\n" +
"\n" +
"");
e.printStackTrace();
}
}
}
}
public static Object load(File binFile) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(binFile));
Object result = ois.readObject();
ois.close();
return result;
}
}
BankData.java:
import java.io.Serializable;
public class BankData implements Serializable {
private static final long serialVersionUID = -8106402506199069298L;
private int bankamount = 0;
public int getBankAmount() {
return bankamount;
}
public void setBankAmount(int value) {
bankamount = value;
}
}
这些文件如何保存:
save(this.bankhandler.get(player.getName()), new File (this.plugin.getDataFolder() + "/bank/", player.getName());
public static void save(Object obj, File binFile) throws Exception {
ObjectOutputStream oops = new ObjectOutputStream(new FileOutputStream(binFile));
oops.writeObject(obj);
oops.flush();
oops.close();
}
这一行:
this.bankhandler.get(player.getName())
返回播放器的BankData实例。
是的,保存的文件使用与此BankData具有相同的serialversionUID,并且是抛出的异常:
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(Unknow
n Source)
at java.io.ObjectInputStream$BlockDataInputStream.refill(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.skipBlockData(Unknown
Source)
at java.io.ObjectInputStream.skipCustomData(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at no.buildnorge.hultberg96.BankReader.BankReader.load(BankReader.java:5
1)
at no.buildnorge.hultberg96.BankReader.BankReader.main(BankReader.java:3
5)
Att,Edvin。