java readLine()读取txt文档,结果缺少每行“首字母”,求解决方法。

比如1.txt内容是
abcd
efg
dsd
读出来的结果是abcfgsd

import java.io.*;
public class read {

public static void main(String[] args) {

try{

String filepath="c:\\1.txt";

BufferedReader fin=new BufferedReader(new FileReader(filepath));
String str="";
while (fin.read()!=-1)
{
str+=fin.readLine();

}
System.out.print(str);
}

catch (Exception e){
e.printStackTrace();
}

}

}
打错了
比如1.txt内容是
abcd
efg
dsd
读出来的结果是bcdfgsd
每行的第一个字母不见了(第一行的a,第二行的e,第三行的d)

package awt;
import java.io.*;
public class read {

public static void main(String[] args) {

try{

String filepath="C:\\1.txt";
// 建议改为:String filepath="C:/1.txt";因为windows操作系统路径分隔符是反斜杠,而linuix
系统是正斜杠,但是今天我告诉你正斜杠/是通用的。很多人都不知道,

BufferedReader fin=new BufferedReader(new FileReader(filepath));
String str=null;

while ((str=fin.readLine())!=null) //此处你用fin.read方法已经读取一个字符了二循环体又用readline方法接着读显然会少一个字符因为你read方法读过一个字符游标就会移动一下
{

System.out.println(str);

}

}

catch (Exception e){
e.printStackTrace();
}

}

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-02
import java.io.BufferedReader;
import java.io.FileReader;

public class read {
public static void main(String[] args) {
try {
String filepath = "1.txt";

BufferedReader fin = new BufferedReader(new FileReader(filepath));
String str = "";
String result = "";
while ((str = fin.readLine()) != null) {
result += str;
}
System.out.print(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}本回答被提问者采纳
第2个回答  2012-03-02
while (fin.read()!=-1)
{
str+=fin.readLine();

}
fin.read()方法会读取一个字符,,,这时你已经读取了第一个字符,,,然后readLine()读取该行的其他字符,,,所以你输出的每行少了第一个字符,,,
可以通过fin.readLine() 返回的是否为null判断是否读取完...
第3个回答  2012-03-02
这是因为你的while (fin.read()!=-1)
{
str+=fin.readLine();

}
中的fin.read()把第一个字母给读取了哦~所以才会出现第一个字母不见了
相似回答