BufferedReader没有读取整个文本文件

时间:2016-06-14 20:07:58

标签: java bufferedreader

                String str = "";
            try {

                BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()));
                while (br.readLine() != null) {
                    str += br.readLine();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String replace = str.replace("HTTP Request: ", "")
                    .replace("Resource URL: ","")
                    .replace("Attribute\t\tDescription", "| Attribute | Type | Description |<P>|----|----|<P>")
                    .replace("Data Type | Max Length | Requirement |", "")
                    .replace("N/A", "Object")
                    .replace("String", "| String")
                    .replace("255 |", "")
                    .replace("Required", "**Required**")
                    .replace("Optional", "**Optional**")
                    .replace("Request Example <P>", "")
                    .replace("Response Example <P>", "Nothing");

            PrintWriter pw = null;

BufferedReader忽略前3行并读取/转换其余行。不确定问题是什么。我已经尝试过其他StackOverflow解决方案,但它们似乎都没有用!

3 个答案:

答案 0 :(得分:4)

问题在于:

while (br.readLine() != null)

检查br.readLine()是否为空时,您已经读过该行。要解决此问题,您可以尝试以下操作:

String line = br.readLine();
while (line != null){
    str +=line;
    line = br.readLine();
}

答案 1 :(得分:2)

您只需检查br.readLine()的返回值,同时您也应该对其进行处理,以下是常用代码:

StringBuider buffer = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
    String line;
    while((line = br.readLine()) != null) {
        buffer.append(line);
    }
}

答案 2 :(得分:0)

theVoid已经告诉了什么问题是一个解决方案。

在cinditional语句是迭代函数的情况下,我总是喜欢使用

do{
    //task
    //Iterate and store result in var, like in your case
    var = br.readLine();
}while(var != null/*check on var rather than executing iteration*/);