How do I turn a FileOutputStream to a File (Java)?

107 views Asked by At

I create a file using a FileOutputStream(), and after creating it I want to check if that file exists.

I have tried to see if there is something like File.exists() for it, I also looked at get file name from fileoutputstream but that solves how to get the filename, which is not my question. So I need a way to turn the FileOutputStream() to a File().

2

There are 2 answers

2
Eddy On

A FileOutputSteam takes either a File as an argument or a filename (which will be converted to a file by the constructor).

If you have a reference to the file, file.exists() should return true, see kotlin code example below:

    fun main(args: Array<String>) {
        val file = File.createTempFile("foo",".txt")
        val fos = FileOutputStream(file)
        fos.write(1)

        println("assert tmpfile exists: ${file.exists()}")
    }
1
sa3khan On

You can instantiate the OutputStream using a Path object. Here's a couple of ways

Using Files:

Path path = Paths.get("/a/b/c");
try(OutputStream os = Files.newOutputStream(path)) {
  Files.exists(path);
}

Using FileOutputStream:

Path path = Paths.get("/a/b/c");
try(FileOutputStream fos = new FileOutputStream(path.toFile())) {
  path.toFile().exists();
}