OutputStream class is used for writing into files. How is it possible?

7.1k views Asked by At

The below code is quoted from : http://examples.javacodegeeks.com/core-java/io/fileoutputstream/java-io-fileoutputstream-example/

Although the OutputStream is an abstract method, at the below code, OutputStream object is used for writing into the file.

Files.newOutputStream(filepath)) returns OutputStream. Then, the type of out is OutputStream, and out references OutputStream.

How can this be possible while OutputStream is an abstract class?

package com.javacodegeeks.core.io.outputstream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileOutputStreamExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        String content = "Hello Java Code Geeks";

        byte[] bytes = content.getBytes();

        Path filepath = Paths.get(OUTPUT_FILE);

        try ( OutputStream out = Files.newOutputStream(filepath)) {

            out.write(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
1

There are 1 answers

4
Jon Skeet On BEST ANSWER

Just because the declared type is OutputStream, that doesn't mean the implementation doesn't create an instance of a concrete subclass of OutputStream. You see this all the time with interfaces. For example:

public List<String> getList() {
    return new ArrayList<String>();
}

Basically you need to distinguish between the API exposed (which uses the abstract class) and the implementation (which can choose to use any subclass it wants).

So Files.newOutputStream could be implemented as:

public static OutputStream newOutputStream(Path path)
    throws IOException {
  return new FileOutputStream(path.toFile());
}