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

你离开我真会死。 提交于 2019-12-12 05:58:28

问题


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:


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


来源:https://stackoverflow.com/questions/30968453/outputstream-class-is-used-for-writing-into-files-how-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!