java 念整数_Java – 从文件中读入字符串和整数 | 学步园

想平时写 C++ 时,从文件中按指定格式读入数据多方便。。

给自己写个 Java 的。。

package lib.com.chalex.www;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

/**

* @author Jiechao

*

*/

public class SReader {

/**

* @remark Constructor.

*/

public SReader(String filepath) {

cur = 0;

try {

String line = new String();

reader = new BufferedReader(new InputStreamReader(

new FileInputStream(filepath)));

while ((line = reader.readLine()) != null && line.trim().equals(""))

;

if (line == null) {

buf = null;

} else {

line = line.trim().replace('\t', ' ');

buf = line.split(" ");

}

} catch (FileNotFoundException e) {

e.printStackTrace();

System.out.println("File not exists!");

} catch (IOException e) {

e.printStackTrace();

System.out.println("File content fuck!");

}

}

/**

* @remark Read a string from the file at this current position.

* @return A string.

*/

public String readString() {

String ret = new String();

if (buf == null) {

return null;

}

if (cur < buf.length) {

while (cur < buf.length && buf[cur].equals("")) {

++cur;

}

ret = buf[cur++];

} else {

try {

String line = new String();

while ((line = reader.readLine()) != null

&& line.trim().equals(""))

;

if (line == null) {

return null;

}

line = line.trim().replace('\t', ' ');

buf = line.split(" ");

cur = 0;

ret = buf[cur++];

} catch (IOException e) {

e.printStackTrace();

System.out.println("File content fuck!");

}

}

return ret;

}

/**

* @remark Read an integer from the file at this current position.

* @return An integer.

*/

public int readInt() {

int ret = 0;

boolean isInt = true;

String s = readString();

if (s == null) {

return -1;

}

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

if (s.charAt(i) < '0' || s.charAt(i) > '9') {

if (i > 0 || (i == 0 && s.charAt(i) != '-')) {

isInt = false;

break;

}

}

}

if (isInt) {

ret = Integer.parseInt(s);

} else {

ret = 0;

}

return ret;

}

private int cur;

private String[] buf;

private BufferedReader reader;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值