【问题标题】:Checking if file exists, if so, dont create new file and append instead检查文件是否存在,如果存在,则不要创建新文件并追加
【发布时间】:2014-05-18 16:09:32
【问题描述】:
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);
    }
 }   

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

【问题讨论】:

标签: java file append


【解决方案1】:

您必须首先检查文件是否存在,如果不存在则创建一个新文件。要了解如何将对象附加到对象流,请查看 question

        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);
        }

【讨论】:

    【解决方案2】:

    使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2017-11-22
      • 1970-01-01
      • 2022-11-06
      • 2021-07-08
      • 2013-02-06
      • 1970-01-01
      相关资源
      最近更新 更多