0

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().

Mac.exe
  • 1
  • 5

2 Answers2

-1

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()}")
    }
Eddy
  • 74
  • 1
  • 9
-3

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