FileDescriptor用Java打开文件

Beg*_*ner -1 java

我想要一个方法,其目的是这样的:

fileDescriptor openFile (filename):将打开一个具有特定名称的文件(如果内容已经存在,将删除该内容)并将"Process of Process"作为第一行; 返回文件描述符

public FileDescriptor openFile(String fileName){
}
Run Code Online (Sandbox Code Playgroud)

谁有人帮我这个?

小智 6

这是怎么做的:

private FileDescriptor openFile(String path)
        throws FileNotFoundException, IOException {
    File file = new File(path);
    FileOutputStream fos = new FileOutputStream(file);
    // remember th 'fos' reference somewhere for later closing it
    fos.write((new Date() + " Beginning of process...").getBytes());
    return fos.getFD();
}
Run Code Online (Sandbox Code Playgroud)

但是,最好返回FileOutputStream实例(也可以从中获取FileDescriptor),因为您可以向文件中添加更多内容并正确关闭它

如果您的方法签名不允许异常,则try-catch并抛出RuntimeException或try-catch异常并返回null(在这种情况下,添加javadoc解释返回null的含义)