java - 使用 Java 读取文本文件会抛出 IOException

标签 java

我编译了我的Java,没有错误,但是,当我想使用java读取文本时,它显示以下错误:

   java countwords Chp_0001.txt <-- this is my action

    Exception in thread "main" java.io.IOException: Stream closed
    at java.io.BufferedReader.ensureOpen(BufferedReader.java:122)
    at java.io.BufferedReader.read(BufferedReader.java:179)
    at countwords.readFile_BSB(assignment.java:164)
    at countwords.main(assignment.java:53)

以下是我的Java输入:

 import java.util.*;
import java.io.*;
class countwords {
public static String [] MWTs ={ "Hong Kong","New York",
"United Kingdom","Basic Law","People's Republic of China",
};

public static void bubble_sort_length(String [] strs){
while (true) {
    int swaps = 0;
    for (int i = 0 ; i<strs.length -1; i++) {
        if (strs[i].length() >= strs[i+1].length())
            continue ;
        String tmp = strs[i];
        strs[i]    = strs[i+1];
        strs [i+1] = tmp;
        swaps++;
    }
    if (swaps ==0) break ;
    }
}

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

    String txt=readFile_BSB(args [0]);
    bubble_sort_length(MWTs);
    txt= underscoreMWTs(txt);
    for (int i = 0 ; i < MWTs.length;i++)
        System.out.println(i + "-->" + MWTs[i]) ;
        System.out.print (txt);

    String [] words = txt.split("\\s+");


    StringBuilder txt_p = new StringBuilder();
    for (String w : words){
        txt_p.append(sep_punct(w));
          }
    words = txt_p.toString().split("\\s+");

    Arrays.sort (words);

    String w ="";
    int cnt =0;
    StringBuilder all_lines = new StringBuilder();
    for(int i = 0;i < words.length;i++){
        if (w.equals(words[i])){
            cnt++ ;
            } else {
            if(!w.equals("")) {
                if (w.contains("_")) {
                    String u = de_underscore (w) ;
                    if(isMWT (u)) w = u ;
                }       
            all_lines.append (addSpaces(cnt) + " " + w + "\r\n");
            }
        w=words[i];
        cnt=1;
         }
        }

String [] lines = all_lines.toString().split ("\r\n");
Arrays.sort(lines);

for (int i= lines.length-1;i>= 0 ; i--) {
    System.out.println(lines[i]);

    }
 }

public static boolean isPunct(char c){
    return ",.':;\"!)?_@(#".contains(""+c);
    }
    public static String sep_punct( String w ) {
    StringBuilder W= new StringBuilder(w);
    String init_puncts = "",end_puncts="";
    char c;
    while (W.length() > 0) {
        c =W.charAt(0);
        if (!isPunct(c)) break;
        W.deleteCharAt(0);
        init_puncts +="" + c + " ";
    }
    while (W.length() > 0) {
        c= W.charAt(W.length () -1);
        if (!isPunct(c)) break;
        W.deleteCharAt (W.length()-1);
        end_puncts += "" +c+"";
    }
return "" + init_puncts + W.toString() + end_puncts +"";
    }
public static String underscoreMWTs(String txt){
    StringBuilder TXT = new StringBuilder(txt);
    for(String mwt : MWTs ) {
        int pos =0 ;
        while ((pos =TXT.indexOf(mwt,pos)) !=-1) {
        pos += mwt.length();
       }
     }
return TXT.toString();
    }
public static void space2underscore (StringBuilder sb, int pos, int lgth){
for (int p = pos; p < pos+lgth; p++ ){
    if (sb.charAt(p) ==' ')
    sb.setCharAt(p,'_');
        }
    }

public static String de_underscore(String w) {
    StringBuilder W = new StringBuilder (w);
    for (int i= 0 ; i < W.length(); i++ ) {
        if ( W.charAt (i) == '_')
             W.setCharAt (i ,' ');
}
        return W.toString ();
}
    public static boolean isMWT (String w) {
       for (String t : MWTs) {
            if (w.equals(t)) return true;
            }
            return false;
}
    public static String addSpaces (int cnt) {
    String s ="" + cnt;
    while (s.length () <10 ) {
    s=" " + s;
    }
    return s;
    }

public static String readFile_BSB(String fn) throws IOException{
FileReader fr= new FileReader(fn);
BufferedReader r= new BufferedReader (fr);
StringBuilder s= new StringBuilder();
int c;
while ((c = r.read()) != -1) {
    s.append ((char)c);
r.close();
}
   return s.toString();

    }
}

请帮助我纠正错误,因为我现在已经绝望了。 非常感谢!

最佳答案

检查 readFile_BSB() 中的循环:

不好

while ((c = r.read()) != -1) {
    s.append ((char)c);
    r.close(); // Close while reading?
}

更好

while ((c = r.read()) != -1) {
    s.append ((char)c);
}
r.close(); // Close after reading.

为什么不好呢?逐字节读取非常慢,如果出现异常,您的流不会关闭...

关于java - 使用 Java 读取文本文件会抛出 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959434/

相关文章:

java - 从 parse.com 接收文本文件并放置在 textview 中

java - 尝试运行 Google 语音识别 java 示例时出现 "need path to queries.json"错误

java - 不关闭 stringwriter 会导致泄漏吗?

java - Eclipse m2eclipse 在依赖项搜索中找不到任何 mysql

java - FlatFileItemWriter 无法创建新文件或更新现有文件

java - 将 ArrayList 转换为 Array - 不确定如何使用它

java - Google Cast - 无法解析 mSelectedDevice

java - 合成器外观中的默认按钮输入映射?

java - Clojure 关键字在内存中的大小是多少?

java - 将 SIFT 用于增强现实