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

2024-12-22 18:09:17
推荐回答(2个)
回答1:

这个容易。下面程序把内容保存到数组里面,其中
[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 list = getFileContent(fileName);//将所有读到的文件放到数组里面

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

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

}

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

String content = "";

List contentList = new ArrayList();
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

回答2:

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());
}}