[英]getting null when reading a text file in java using buffered reader
我在读取java中的文本文件并将其分配给数组时遇到问题。 该程序正在运行,但我得到null。 我尝试将代码更改为最简单的代码,就像您在下面看到的那样。 因为这个应该真正循环文本文件。 但我这样做是为了让我很容易看出问题出在哪里。 但问题是我不知道为什么它仍然输出null。
该文件肯定在我指定的目录中,因为当我使用以下方法检查它时,内置方法存在返回true:
if(ofile.exists()==true){
System.out.println("exist");
}else{
System.out.println("not exist");
}
请我帮忙,确定这背后的错误,为什么它返回null。
public static void main(String args[]){
String[] eq=new String[50];
String[]ea=new String[50];
String[]eb=new String[50];
String[] ec=new String[50];
String[]ed=new String[50];
char[] ans=new char[50];
String strtemp;
File ofile= new File("J:\\questions.txt");
BufferedInputStream bis= null;
FileInputStream fis= null;
DataInputStream dis=null;
int ii=0;
int score=0;
System.out.println(eq[1] + "\n" + ea[1] + "\n" + eb[1] + "\n" + ec[1] + "\n" + ed[1] + "\n" + "\n" + "Answer: ");
String strans=x.nextLine();
char y=strans.charAt(0);
if(y==ans[1]){
score++;
}else{
}
try{
fis=new FileInputStream(ofile);
bis=new BufferedInputStream(fis);
dis=new DataInputStream(bis);
while(dis.available()!=0){
eq[1]=dis.readLine(); ea[1]=dis.readLine();
eb[1]=dis.readLine(); ec[1]=dis.readLine();
ed[1]=dis.readLine(); strtemp=dis.readLine();
ans[1]=strtemp.charAt(0);
}
bis.close();
dis.close();
fis.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
我想我有类似的问题。 据我所知, dis.available
返回0,即使有文本要读。 尝试在缓冲区中读取内容。
以下是使用BufferedReader在Java中读取文本文件的方法:
BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( "J:\\\\questions.txt") ); String line = null; do { line = reader.readLine(); if( line != null ) { // Do Something with line } } while( line != null ); } catch (Exception e) { e.printStackTrace(); } finally { if( reader != null ) try { reader.close(); } catch (IOException e) { } }
`available'在javadoc中描述为
int available()返回可以从此输入流中读取(或跳过)的字节数的估计值,而不会被下一次调用此输入流的方法阻塞。
它最初会变为0,因为你还没有读过它。 不要使用available
于此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.