简体   繁体   English

从文件中读取字符

[英]reading characters from file

I'm having trouble understanding why my code isn't working properly.Just to test it, I have only five characters in my txt file. 我无法理解为什么我的代码无法正常工作。只是为了测试它,我的txt文件中只有五个字符。 I know that characters are being put into array I create, but I am not sure why wouldnt it print them. 我知道字符被放入我创建的数组中,但我不确定为什么不打印它们。 Thanks! 谢谢!

        catch (IOException exception) {
            System.err.println(exception);
        }// catch

        finally {
            try {
                if (fileInput != null)
                    fileInput.close();
            }// try

            catch (IOException exception) {
                System.err.println("error!" + exception);
            }// catch

        }// finally

    }// main
}// TestCode

You have a for loop inside your while reader loop. 你的while阅读器循环中有一个for循环。 Better to use: 更好用:

    int index = 0;
    while ((character = fileInput.read()) != -1) {
        inputArray[index] = (char) character;
        index++;
    }

Also ensure that you dont exceed the inputArray size. 还要确保不要超过inputArray大小。 You may want to consider a using a List type if this data is required to grow. 如果需要增长此数据,您可能需要考虑使用List类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM