日期:2014-05-20  浏览次数:20800 次

[在线等]求救,读取文本文件时,readLine认为“回车符”是一行结束的问题
本帖最后由 kerafan 于 2013-08-14 15:19:40 编辑
我有个文件,里面有三个字段,用|分割,例如内容是:030105010500154859_01|小港新村干#06杆台架[回车符]|02[换行符]。
因为中间那个字段有个回车符,所以用BufferedReader的readLine方式,会读出两行来:
第一行:030105010500154859_01|小港新村干#06杆台架
第二行:|02
我本来是想读出成一个String,然后按照“|”分隔符分割成三个字段。现在不知道怎么做了?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class UTest1 {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("1.txt")));
String line = null;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
try {
br.close();
} catch (IOException e1) {
}
}
}
}

------解决方案--------------------
看来你是使用split的时候出的问题吧!
你看下这样:

public static void main(String[] args) {


StringBuffer sub=new StringBuffer();
BufferedReader br=null;
try {
br=new BufferedReader(new FileReader(new File("f:/1.txt")));
String line=null;

while((line=br.readLine())!=null)
{
sub.append(line+"");
}

String r=sub.toString();

String [] result=r.split("\\
------解决方案--------------------
");

for (int i = 0; i < result.length; i++) {

System.out.println(result[i]);

}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block