使用缓冲读取器读取java中的文本文件时获取null
我在java中读取文本文件并将其分配给数组时遇到问题。 程序正在运行,但我得到空值。我试着将代码更改为最简单的,就像下面看到的一样。因为这个应该在文本文件中循环。但我这样做是为了让我能很容易地看到问题出在哪里。但问题是,我不知道为什么它仍然输出null 该文件肯定位于我指定的目录中,因为当我使用以下方法检查时,内置方法exists返回true:使用缓冲读取器读取java中的文本文件时获取null,java,arrays,text-files,bufferedreader,Java,Arrays,Text Files,Bufferedreader,我在java中读取文本文件并将其分配给数组时遇到问题。 程序正在运行,但我得到空值。我试着将代码更改为最简单的,就像下面看到的一样。因为这个应该在文本文件中循环。但我这样做是为了让我能很容易地看到问题出在哪里。但问题是,我不知道为什么它仍然输出null 该文件肯定位于我指定的目录中,因为当我使用以下方法检查时,内置方法exists返回true: if(ofile.exists()==true){ System.out.println("exist"); }else{ System.out.pri
if(ofile.exists()==true){
System.out.println("exist");
}else{
System.out.println("not exist");
}
请我需要帮助,确定这背后的错误,为什么它返回空
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可用()
返回可从此输入流读取(或跳过)的字节数的估计值,而无需在下次调用此输入流的方法时阻塞
它最初将为0,因为您尚未从中读取。不要为此使用可用的
。+1。如果您曾经使用过available()
,并且在功能上依赖于它返回的内容,那么您可能做错了什么。始终返回0
是available()
的完美兼容实现。