检查文件是否存在,如果存在,请不要创建新文件并追加


private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
    name = nameFormText.getText();
    surname = surnameFormText.getText();
    age = Integer.parseInt(ageFormText.getText());
    stadium = stadiumFormText.getText();
    Venues fix = new Venues();
    fix.setName(name);
    fix.setSurname(surname);
    fix.setAge(age);
    fix.setStadium(stadium);
    File outFile;
    FileOutputStream fStream;
    ObjectOutputStream oStream;
    try {
        outFile = new File("output.data");
        fStream = new FileOutputStream(outFile);
        oStream = new ObjectOutputStream(fStream);
        oStream.writeObject(fix);
        JOptionPane.showMessageDialog(null, "File written successfully");
        oStream.close();
    } catch (IOException e) {
        System.out.println(e);
    }
 }   

这就是我目前所拥有的。如果已经创建文件,我可以用它做什么来附加文件的任何想法?

您必须先检查该文件是否存在,如果没有创建一个新文件。要了解如何将对象附加到对象流,请查看此问题。

        File outFile = new File("output.data");
        FileOutputStream fStream;
        ObjectOutputStream oStream;
        try {
            if(!outFile.exists()) outFile.createNewFile();
            fStream = new FileOutputStream(outFile);
            oStream = new ObjectOutputStream(fStream);
            oStream.writeObject(fix);
            JOptionPane.showMessageDialog(null, "File written successfully");
            oStream.close();
        } catch (IOException e) {
            System.out.println(e);
        }

使用 Java 7,它很简单:

final Path path = Paths.get("output.data");
try (
    final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);
    final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
    // work here
} catch (IOException e) {
    // handle exception here
}

放下File

相关内容

  • 没有找到相关文章

最新更新