JAVA读取文件的一个小问题
为啥会抛出FileNotFoundException异常呢?importjava.io.BufferedReader;importjava.io.FileNotFound...
为啥会抛出FileNotFoundException异常呢?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class One {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("sd.txt"));
while(true){
String str = br.readLine();
if(str.equals("over")){
try {
br.close();
} catch (Exception e) {}
break;
//System.exit(0);
}
System.out.println(str);
}
}
}
文件sd.txt的内容是:
vsavas
sfafs
输出是:
vsavas
sfafs
Exception in thread "main" java.lang.NullPointerException
at ff.One.main(One.java:19) 展开
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class One {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("sd.txt"));
while(true){
String str = br.readLine();
if(str.equals("over")){
try {
br.close();
} catch (Exception e) {}
break;
//System.exit(0);
}
System.out.println(str);
}
}
}
文件sd.txt的内容是:
vsavas
sfafs
输出是:
vsavas
sfafs
Exception in thread "main" java.lang.NullPointerException
at ff.One.main(One.java:19) 展开
2个回答
推荐于2016-10-21
展开全部
你的提问应该是:为什么会抛出NullPointerException?
因为你的是最后一行就是null,所以会抛出空指针异常;
写代码如下:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class One
{
public static void main ( String[] args ) throws IOException
{
BufferedReader br = new BufferedReader (new FileReader ("sd.txt"));
String str = null;
while (null != ( str = br.readLine () ))
{
if ("over".equals (str))
{
try
{
br.close ();
}
catch (Exception e)
{}
break;
}
System.out.println (str);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询