我想从criteria.txt文件中读取 ,以标记化并在同一文件的末尾附加标记.该程序抛出异常:No file found!我不知道我的错误在哪里.任何建议都会对我有所帮助.先感谢您!
这是我的代码:
import java.io.*;
import java.util.StringTokenizer;
public class Test
{
private FileReader fr;
private BufferedReader br;
private FileWriter fw;
private BufferedWriter bw;
private StringTokenizer strtok;
private String s;
//constructor
public Test()
{
try
{
fw=new FileWriter("criteria.txt", true);
bw=new BufferedWriter(fw);
try
{
fr=new FileReader("criteria.txt");
br=new BufferedReader(fr);
while((s=br.readLine())!=null)
{
strtok=new StringTokenizer(s," ");
while(strtok.hasMoreTokens())
{
bw.write("\n"+strtok.nextToken());
}
br.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File was not found!");
}
catch(IOException e)
{
System.out.println("No file found!");
}
bw.close();
}
catch(FileNotFoundException e)
{
System.out.println("Error1!");
}
catch(IOException e)
{
System.out.println("Error2!");
}
}
public static void main(String[] args)
{
Test t=new Test();
}
}
Run Code Online (Sandbox Code Playgroud)
完成读取文件后,即在while循环后,您需要关闭阅读器.目前,您在读取第一行后关闭它,IOException: Stream closed当它尝试读取第二行时会产生" ".
改成:
while((s=br.readLine())!=null)
{
strtok=new StringTokenizer(s," ");
while(strtok.hasMoreTokens())
{
bw.write("\n"+strtok.nextToken());
}
//br.close(); <----- move this to outside the while loop
}
br.close();
Run Code Online (Sandbox Code Playgroud)