我有一个程序从文件中读取内容并将其打印在屏幕上。但程序打印每隔一行,即每隔一行跳过一次。 包InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private PrintWriter pw = new PrintWriter(System.out, true);
/* Read from file and print to console */
public void readFromFile() throws IOException{
try{
br = new BufferedReader(new FileReader("E:\\Programming\\Class files\\practice\\src\\InputOutput\\test.txt"));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
String s = null;
do{
s = br.readLine();
pw.println(s);
}
while((s = br.readLine())!=null);
br.close();
}
/* Main method */
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.readFromFile();
}
}
答案 0 :(得分:6)
你为什么要做s=br.readline()
两次......你可以这样做。
String s = null;
while((s = br.readLine())!=null)
{
pw.println(s);
}
每次调用它时, readline()
都会读取一行,然后转到下一行。所以当你两次打电话时,显然你正在跳过一条线。使用此代码,它将工作。
答案 1 :(得分:1)
你循环错误:
String s = null;
do{
s = br.readLine();
pw.println(s);
}
while((s = br.readLine())!=null);
应该是:
String s = null;
while((s = br.readLine())!=null) {
pw.println(s);
};
答案 2 :(得分:1)
撤消您的do/while
循环以避免两次调用readline
并丢弃所有其他结果:
String s = null;
while((s = br.readLine())!=null) {
pw.println(s);
}
答案 3 :(得分:0)
删除执行循环的第一行。你两次调用readLine()。
即:
String s = null;
while((s = br.readLine())!=null) {
pw.println(s);
}
答案 4 :(得分:0)
如果您想使用do-while,则需要修改do-while循环,然后按如下方式对其进行编码。
String s = null;
do{
pw.println(s);
}
while((s = br.readLine())!=null);
br.close();
答案 5 :(得分:0)
更改:
for(String s; (s = br.readLine()) != null;) {
pw.println(s);
}
答案 6 :(得分:0)
你正在使用br.readLine()两次。
String s = null;
do{
s = br.readLine(); //here it read first line
pw.println(s); //here it prints first line
}
while((s = br.readLine())!=null); //here s read second line
//note that it is not printing that line
String s = null;
do{
s = br.readLine(); //this time it read third line
pw.println(s); //now it prints third line
}
while((s = br.readLine())!=null); // this time it reads fourth line
因此,此过程将继续,您的程序将逐个打印行