我想用java编写程序,我想用二进制文件来保存数据。该程序将使用两种类型的数据 - 日期,这将是一个字符串和金额将是两倍。我想:
我试图创建文件,写入并读取它(我正在检查其他方法中存在的文件,所以不要担心)并且我遇到了多个问题。
我仍然非常缺乏经验。我一直在寻找解决方案,但我找不到它。所以我想寻求你的智慧,并请求你的帮助。谢谢!
static final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
static Date date = new Date();
try{
final Formatter filecreation = new Formatter("sData.bin");
filecreation.close();
DataOutputStream datafill = new DataOutputStream(new FileOutputStream("sData.bin"));
datafill.writeChars(dateFormat.format(date));
datafill.writeDouble(0.00);
//Debug
System.out.println("File created");
}
catch(Exception a) {
JOptionPane.showMessageDialog(null, "File has not been created","Error", JOptionPane.WARNING_MESSAGE);
}
@SuppressWarnings("deprecation")
static public void readfile () {
String finaldate = "";
Double amount = 0.00;
try {
DataInputStream in = new DataInputStream(new FileInputStream("sData.bin"));
finaldate = in.readLine();
while(in.available() > 0) {
amount = in.readDouble();
}
System.out.println("You have spend" + amount);
in.close();
}
catch (Exception e) {
System.out.println("Something went wrong");
}
编辑:感谢您的信息,我终于设法正确地编写和阅读了所有内容。但我仍然没有设法覆盖二进制文件中的double值。现在它看起来像这样,并且在我尝试覆盖double之后总是不可避免地抛出异常
String finaldate = "";
Double amount = 0.00;
try {
// create a new RandomAccessFile with filename test
RandomAccessFile sDataRAF = new RandomAccessFile("sData.bin", "rws");
DataInputStream in = new DataInputStream(new FileInputStream("sData.bin"));
for (int c = 0; c < 10; c++) {
finaldate += in.readChar();
}
System.out.println(finaldate.length());
System.out.println(finaldate);
amount = in.readDouble();
System.out.println(amount);
//overwrite double
sDataRAF.seek(10);
sDataRAF.writeDouble(30.0);
amount = in.readDouble();
System.out.println(amount);
in.close();
sDataRAF.close();
}
catch (Exception e) {
System.out.println("Something went wrong");
}