为什么我必须在创建对象时创建类型为FileReader / Writer的inputStream和outputStream? [英] Why must I create inputStream and outputStream with type FileReader/Writer when im creating the objects themselves?

查看:106
本文介绍了为什么我必须在创建对象时创建类型为FileReader / Writer的inputStream和outputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的这是代码,我的问题是为什么我必须把 FileReader inputstream = null; FileWriter 。为什么我不能在try块中稍后创建对象?我错过了什么......我可能是。

Ok this is the code and my question is why do i have to put FileReader inputstream = null; and the same with FileWriter. Why can't I simply create the objects later in the try block? Am I missing something... I probably am.

public static void main(String[] args) throws IOException{
    // TODO Auto-generated method stub
        FileReader inputStream = null;
        FileWriter outputStream = null;
        try {
            inputStream = new FileReader("In.txt");
            outputStream = new FileWriter("Out.txt");
            int c;
            while ((c = inputStream.read()) != -1){
                outputStream.write(c);

            }
        }
                finally {
                    if (inputStream != null){
                        inputStream.close();
                    }
                    if (outputStream != null){
                        outputStream.close();

                }
        }


推荐答案

因为您无法在 finally 块中引用它们,因此您将无法关闭它们。

Because you won't be able to refer to them in the finally block, and so you won't be able to close them.

顺便说一句,如果他们是读者和作家,你最好用这种方式命名变量,而不是 xStream

Btw, if they are reader and writer, you'd better name the variables that way, rather than xStream.

I / O处理一直很乏味,这就是为什么Java 7引入尝试使用资源

I/O handling has always been tedious, that's why Java 7 introduced "try with resource"

这篇关于为什么我必须在创建对象时创建类型为FileReader / Writer的inputStream和outputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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