我有一個方法,將int存儲在.dat文件中(除此之外),稍後我嘗試使用其他方法檢索該文件,並給出了一個荒謬的值。例如,如果我嘗試存儲1,則另一個方法將檢索到484449.我是Java新手,如果這是正常的,請解釋。ReadInt()返回荒謬值
方法寫入INT:
public static int fromText (String textRefference, String binaryRefference,
boolean overwrite, String countRefference){
if(!(new File(binaryRefference).exists()))overwrite = true;
BufferedReader input;
ObjectOutputStream output;
ObjectInputStream binaryInput;
ObjectInputStream countStreamI;
ObjectOutputStream countStreamO;
int count = 0;
try{
input = new BufferedReader(new FileReader(textRefference));
String[] data = null;
int oldCount = 0;
if(!overwrite){
countStreamI = new ObjectInputStream(new FileInputStream(countRefference));
binaryInput = new ObjectInputStream(new FileInputStream(binaryRefference));
oldCount = countStreamI.readInt();
data = new String[oldCount];
int i;
for(i = 0;i < oldCount; i++){
data[i] = binaryInput.readUTF();
}
countStreamI.close();
}
countStreamO = new ObjectOutputStream(new FileOutputStream(countRefference));
output = new
ObjectOutputStream(new FileOutputStream(binaryRefference));
String sentinel = input.readLine();
String[] data2 = new String[1500];
while(!sentinel.equalsIgnoreCase("end")){
System.out.println(sentinel + " has been recorded");
data2[count] = sentinel;
sentinel = input.readLine();
count++;
}
count += oldCount;
countStreamO.writeInt(count);
if(!overwrite){
int i;
for(i = 0; i < oldCount;i++){
output.writeUTF(data[i]);
}
}
int i = 0;
for(; i < count + oldCount;i++){
output.writeUTF(data2[i]);
}
output.flush();
countStreamO.flush();
countStreamO.close();
output.close();
input.close();
}
catch(Exception e){
Scanner in = new Scanner(System.in);
e.printStackTrace();
in.nextLine();
System.exit(0);
}
return count;
}'
,功能取回:
public static String[] pullStrings(String file, String countReferrence, boolean print){
String[] data = null;
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
int count = input.readInt();
data = new String[count];
int i = 0;
String string;
for(;i < count; i++){
string = input.readUTF();
if(print)System.out.println(string);
data[i] = string;
}
}
catch(Exception e){
Scanner in = new Scanner(System.in);
System.out.println(e.getMessage() + "\n\n");
e.printStackTrace();
System.out.println("\n hit ENTER to exit.");
in.nextLine();
System.exit(0);
}
return data;
}
而且文本文件:
data!!!
end
你的問題基本上是,'「這是爲什麼我不顯示你不工作的代碼?」'。請通過創建併發布您的[mcve]來解決此問題。 –
如果出現錯誤,請務必發佈您的代碼和錯誤。一個簡單的描述不足以幫助你 –
你可以與我們分享功能嗎?沒有代碼示例,真的很難幫助你。 – wmk