简体   繁体   English

使用Java读取文本文件会引发IOException

[英]Reading a text file using Java throws IOException

I have compiled my Java with no error , However, when I want to use the java to read the text , it shows the following error : 我已经编译了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)

The following is my input of Java : 以下是我对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();

    }
}

Please help me with the errors as I am quite hopeless at this point . 请帮助我解决错误,因为我现在绝望了。 Thank You so much ! 非常感谢 !

Check your loop in readFile_BSB(): 检查readFile_BSB()中的循环:

BAD

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

BETTER 更好

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

Why not good? 为什么不好? Reading byte by byte is very slow, in case of Exception your streams are not closed... 逐字节读取非常慢,如果出现异常,则流不会关闭...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM