【问题标题】:getting null when reading a text file in java using buffered reader使用缓冲阅读器在java中读取文本文件时获取null
【发布时间】:2011-04-20 19:58:28
【问题描述】:

我在读取 java 中的文本文件并将其分配给数组时遇到问题。 该程序正在运行,但我得到空值。我尝试将代码更改为最简单的代码,就像您在下面看到的一样。因为这个应该真正循环遍历文本文件。但是我这样做是为了让我很容易看到问题出在哪里。但是问题是不知道为什么还是输出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();

    }


    }

【问题讨论】:

    标签: java arrays text-files bufferedreader


    【解决方案1】:

    我想我也有类似的问题。据我所知,即使有文本要阅读,dis.available 也会返回 0。 尝试读取缓冲区中的内容。

    【讨论】:

    • +1。如果您曾经使用过available() 并且在功能上依赖于它返回的内容,那么您可能做错了什么。始终返回0available() 的完美兼容实现。
    【解决方案2】:

    以下是使用 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) {
                }
        }
    

    【讨论】:

      【解决方案3】:

      `available' 在 javadoc 中被描述为

      int 可用() 返回此输入流的下一次调用该输入流的方法时可以从该输入流中读取(或跳过)而不会阻塞的字节数的估计值。

      它最初将为 0,因为您还没有读取它。不要为此使用available

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 2013-04-17
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        • 2021-06-30
        相关资源
        最近更新 更多