java 读文件 数字,Java:如何从文件中读取文本和数字

I am creating a simple program to data read from a text file. The file stores information about a person, with the name, age and a number on each line:

Eg: File format per line

Francis Bacon 50 2

I can read in a file no problem if it is just text, but I am confused on how to differentiate between text and numbers. Here is a look at my code:

import java.io.*;

public class Test{

private People people[] = new People[5];

public Test(){

BufferedReader input;

input = new BufferedReader(new FileReader("People.txt"));// file to be readfrom

String fileLine;

int i = 0;

while (test != null){

fileLine = input.readLine();

// Confused as to how to parse this line into seperate parts and store in object:

// eg:

people[i].addName(fileLine - part 1);

people[i].addBookNo(fileLine - part 2);

people[i].addRating(fileLine - part 3)

i++

}

}

}

解决方案

I strongly suggest you use the Scanner class instead. That class provides you with methods such as nextInt and so on.

You could use it to read from the file directly like this:

Scanner s = new Scanner(new File("People.txt"));

while (s.hasNext()) {

people[i].addName(s.next());

people[i].addBookNo(s.nextInt());

people[i].addRating(s.nextInt());

}

(Just realized that you may have spaces in the name. That complicates things slightly, but I would still consider using a scanner.)

An alternative solution would be to use a regular expression and groups to parse the parts. Something like this should do:

(.*?)\s+(\d+)\s+(\d+)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值