reader return line space between every line when print the lines of textfile

时间:2016-02-20 19:48:49

标签: java bufferedreader

I want to retrieve the lines from text file like this:

line one
line two 
line three

but the output is like this :

line one
space line
line two
space line
line three

and this is my code:

BufferedReader br = null;
try {
                br = new BufferedReader(new FileReader("/users/Moath Ibrahem/Desktop/Questions.txt"));
                System.out.println(br.readLine());
                System.out.println(br.readLine());
                System.out.println(br.readLine());
                System.out.println(br.readLine());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

1 个答案:

答案 0 :(得分:2)

我认为您的文件中存在空白行,因为您正在阅读和打印所有内容,所以它也会打印空白行。

如果您想避免打印空行,则可以在打印前检查空白行。

以下是更正后的代码段:

BufferedReader br = null;
try {
        br = new BufferedReader(new FileReader("/users/Moath Ibrahem/Desktop/Questions.txt"));
        String str = br.readLine();
        if(!str.equals("")) {
            System.out.print(str);
        }
        /* Repeat */
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

输出:

line one
line two 
line three