如果我要读取一个txt文件,并获取其中的三个字段,请问JAVA代码怎么写,谢谢!

txt文件内容如下:
id num code city cardtype
1 1368314 010 北京市 北京移动神州行卡
2 1370102 010 北京市 北京移动全球通卡
3 1368323 010 北京市 北京移动全球通卡
4 1368322 010 北京市 北京移动神州行卡
5 1368321 010 北京市 北京移动神州行卡
6 1368320 010 北京市 北京移动神州行卡
7 1368319 010 北京市 北京移动神州行卡
8 1368318 010 北京市 北京移动神州行卡
9 1368317 010 北京市 北京移动神州行卡
10 1368325 010 北京市 北京移动神州行卡

这个容易。下面程序把内容保存到数组里面,其中
[0] = id, [1] = num, [2] = code, [3] = city, [4] = cardtype
想要哪3段就根据对应的下标遍历数组就可以了

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadTxt {

public static void main(String[] args) throws IOException {

String fileName = "data.txt";//要读取的txt文件
List<String[]> list = getFileContent(fileName);//将所有读到的文件放到数组里面

String[] ary = list.get(1);//第一行是标题,所以取第二行

for(String str: ary){
System.out.println(str);//想取其中的任何一段只要按照数组的下标拿就可以了
}

}

private static List<String[]> getFileContent(String fileName) throws FileNotFoundException, IOException {
File file = new File(fileName);
BufferedReader bf = new BufferedReader(new FileReader(file));

String content = "";

List<String[]> contentList = new ArrayList<String[]>();
while(content != null){
content = bf.readLine();

if(content == null){
break;
}

if(!content.trim().equals("")){
contentList.add(content.trim().split("\\s+"));
}

}

bf.close();

return contentList;
}
}

-----------------
1
1368314
010
Beijing
Shenzhouxing追问

谢谢,不过汉字有乱码,怎么转码?

追答

byte[] ary = content.getBytes("ISO-8859-1"); 用ISO-8859-1试一下,

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-02
br = new BufferedReader(new FileReader("D:\\1.txt"));
String temp = null;

while ((temp = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(temp);
if(st.countTokens() == 4){
System.out.println(st.nextToken());
}}
相似回答