java - 无法在java中关闭我的DataInputStream和DataOutputStream

标签 java file-io file-handling

我最近开始学习java中的文件处理。但是,在这段代码(如下)中,我试图在所有读写结束时关闭文件,但这样做时遇到错误。

package trycatch;

import java.util.Scanner;
import org.omg.CORBA.DataInputStream;

import java.*;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;

public class Source {

public static void main(String[] args) throws Exception {

    Scanner input = new Scanner(System.in);
    try {
    File f = new File("record.txt");

    FileOutputStream writing = new FileOutputStream(f);
    DataOutputStream write = new DataOutputStream(writing);
    write.writeUTF("What are the things that you want to do");

    String str;

    FileInputStream reading = new FileInputStream(f);
    java.io.DataInputStream read = new java.io.DataInputStream(reading);
    str = read.readUTF();
    System.out.println(str);
    }
    catch(FileNotFoundException e) {

        System.out.println("The system collapsed");
    }
    finally {
        write.close(); // write cannot be resolved
        read.close();  // read cannot be resolved
    }

    input.close();
}
}

我正在尝试使用 finally 关键字,但是您能告诉我为什么当我在那里写入时,我的 IDE 无法识别读取写入吗?

write cannot be resolved

最佳答案

你的读写字段对于try block 来说是本地的,finally无法访问then。在try之外初始化它。

关于java - 无法在java中关闭我的DataInputStream和DataOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45309197/

相关文章:

C 编程 : How to read the whole file contents into a buffer

c++ - 如何为长时间运行的程序做文件输出

python - 这段 Python 代码块的作用是什么?

perl - Perl 中 '>>' 和 '>' 的区别

java - Java : Find Inappropriate Exception Handling 的 Coverity 静态分析

java - wget 不通过 Runtime.getRuntime.exec(String[] commandArray) 显示输出

java - 构建 Jar - 如何包含资源文件? IntelliJ 2017

perl 输出 - 无法正确打印 utf8 文本文件

java - 如何在android中逐行阅读?

java - 用于 Android 应用程序开发的最佳 IDE(Netbeans 或 eclipse)?