Java读取文件,如果不存在则创建它

2024-04-03

这是我的代码

public String path;
public String fileName;
public static void readData() throws IOException{
    try {
        path="myPath"
        fileName="myFileName";
        fstream = new FileInputStream(path+fileName);
        br = new BufferedReader(new InputStreamReader(fstream));
        //do something...//
        }
        br.close();
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Reading file error");
        Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

我想知道如何检查 fstream 是否存在。如果不存在,则必须创建一个新文件。我怎样才能做到这一点? 谢谢


这是一个可能的解决方案:

public static void readData() throws IOException
{
    File file = new File(path, filename);

    if (!file.isFile() && !file.createNewFile())
    {
        throw new IOException("Error creating new file: " + file.getAbsolutePath());
    }

    BufferedReader r = new BufferedReader(new FileReader(file));

    try 
    {
        // read data
    }finally
    {
        r.close();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java读取文件,如果不存在则创建它 的相关文章

随机推荐