Java IOException-流关闭 [英] Java IOException - Stream Closed

查看:175
本文介绍了Java IOException-流关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此程序时,我得到"IOException:流关闭" .文本包含许多行数据.程序应读取每一行,执行必要的功能,然后将输出写入新文件.我对于应该首先关闭哪个作者以及在哪里关闭感到困惑.

I get "IOException: Stream Closed" when I run this program. The text contains many lines of data. Program should read each line, do necessary function and write the output to a new file. I am confused as to which writer should be closed first and where.

import java.net.*; 
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {
        BufferedReader br = null;
        try {
            // change this value
            FileInputStream fis = new FileInputStream("C:\\Users\\Rao\\Desktop\\test.txt");
            br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                processLine(sCurrentLine); //error
            }
        } finally {
            if (br != null)
                br.close();
        }
    }

    public static void processLine(String line) throws IOException {
        String prename = line.substring(22);
        int siz= prename.indexOf(":");
        String name = prename.substring(0, siz);

        URL oracle = new URL("http://ip-api.com/json/"+name);
        BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) // error
            // System.out.println(inputLine);
            in.close();  
        String baby = (line + "\t" + inputLine); 

        try {
            FileWriter writer = new FileWriter("C:\\Users\\Rao\\Desktop\\output.txt", true);
            writer.write(baby);
            writer.write("\r\n");   // write new line
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

例外情况如下:

Exception in thread "main" java.io.IOException: Stream closed
    at java.io.BufferedReader.ensureOpen(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at URLReader.processLine(URLReader.java:31)
    at URLReader.main(URLReader.java:13)

推荐答案

您在循环中关闭输入流:

You close the input stream in your loop:

while ((inputLine = in.readLine()) != null) // error

               // System.out.println(inputLine);
in.close();  

您应该在循环外部关闭流:

You should close the stream outside of the loop:

while ((inputLine = in.readLine()) != null) // error
{
   //dosomething
   // System.out.println(inputLine);
}
in.close();  

这篇关于Java IOException-流关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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