OutputStream类用于写入文件。这怎么可能? [英] OutputStream class is used for writing into files. How is it possible?

查看:891
本文介绍了OutputStream类用于写入文件。这怎么可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码引用自: http: //examples.javacodegeeks.com/core-java/io/fileoutputstream/java-io-fileoutputstream-example/

虽然OutputStream是一个抽象方法,在下面的代码中,OutputStream对象用于写入文件。

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

Files.newOutputStream(filepath))返回OutputStream。然后,out的类型是OutputStream,out引用OutputStream。

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

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


推荐答案

仅仅因为声明的类型是 OutputStream ,这并不意味着实现不会创建的实例 OutputStream 的具体子类。你一直看到这个接口。例如:

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

基本上你需要区分暴露的API(使用抽象类)和实现(可以选择使用它想要的任何子类)。

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

所以 Files.newOutputStream 可以实现as:

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

这篇关于OutputStream类用于写入文件。这怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆