你好/我是新来的Java和我试图做一个程序,解析通过一个TXT文件,并逐行扫描其内容。那么,在乞讨中,我设计的程序没有任何对象或类与主分开,它工作正常。然后我想用主函数的内容设计一个新类,但是它不能编译,并且我得到了很多exent错误。下面是代码:在不同的功能Java异常
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Reader {
Reader(String file) throws Exception{
Entry test= new Entry();
File f= new File("C:/Users/Mario/Documents/Visual Studio 2013/Projects/Entry/Entry/a.txt");
System.out.print(f.exists()); // true is printed on the screen when this was at main
FileInputStream fstream = new FileInputStream("C:/Users/Mario/Documents/Visual Studio 2013/Projects/Entry/Entry/a.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String tag="";
String date="";
int id;
String title="",description="",reference="";
while ((strLine = br.readLine()) != null){
System.out.print(strLine+ "\n");
if(strLine.length()>2 && strLine.substring(0,3).equals("I1:")){
System.out.print("id detected\n");
id=-1;
strLine = br.readLine();
id=Integer.parseInt(strLine);
//System.out.print("ID:"+id+"\n");
test.set_id(id);
continue;
}
if(strLine.length()>2 && strLine.substring(0,3).equals("T1:")){
System.out.print("title detected\n");
title="";
strLine = br.readLine();
title=strLine;
//System.out.print("Title:"+title+"\n");
test.set_title(title);
continue;
}
if(strLine.length()>2 && strLine.substring(0,3).equals("D1:")){
System.out.print("description detected\n");
StringBuilder descrp=new StringBuilder();
description="";
while(true){
strLine = br.readLine();
if(strLine.equals("D2:")) break;
else descrp.append(strLine);
continue;
}
description=descrp.toString();
//System.out.print(description);
test.set_description(description);
}
if(strLine.length()>2 && strLine.substring(0,3).equals("D3:")){
System.out.print("DATE"+date);
strLine = br.readLine();
date=strLine;
test.set_date(date);
}
if(strLine.length()>2 && strLine.substring(0,3).equals("R1:")){
strLine = br.readLine();
reference=strLine;
System.out.print("Reference"+reference);
test.set_reference(reference);
}
br.close();
}
}
}
,这些都是我收到错误:
true
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 Reader.<init>(Reader.java:28)
at FileReader.main(FileReader.java:14)
什么困惑我的是,我收到了这些错误,当我改变了文件中的代码是事实。编译前没有错误,程序运行良好。新文件(Reader.java)与主函数所在的文件位于相同的目录中。我在Eclipse IDE上工作。 THX在advnace
编辑:我添加的功能抛出异常,从而改变了控制台输出
所以...你为什么要在构造函数中做所有的事情?另外,这个异常非常简单 - 因为你在那里使用的是一个文件,你可以在'try ... catch'块中包含文件的用法,或者在方法的签名中添加'throws IOException' ,在这种情况下,将会是你的构造函数)。 – Makoto
我不知道为什么在我将这段代码移动到另一个文件之前没有例外。主要是没有这个问题。 – JmRag
我敢打赌,'main'有一个'throws'或者'try ... catch'块。如果没有,你的主要方法也不会编译。 – Makoto