reader return 行 space 打印文本文件行时每行之间
reader return line space between every line when print the lines of textfile
我想像这样从文本文件中检索行:
line one
line two
line three
但输出是这样的:
line one
space line
line two
space line
line three
这是我的代码:
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();
}
我认为您的文件中存在空白行,并且由于您正在阅读和打印所有内容,它也会打印空白行。
如果你想避免打印空行,那么你可以在打印之前检查空行。
这是更正后的代码片段:
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
我想像这样从文本文件中检索行:
line one
line two
line three
但输出是这样的:
line one
space line
line two
space line
line three
这是我的代码:
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();
}
我认为您的文件中存在空白行,并且由于您正在阅读和打印所有内容,它也会打印空白行。
如果你想避免打印空行,那么你可以在打印之前检查空行。
这是更正后的代码片段:
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