现在的位置: 首页 > 综合 > 正文

Java – 从文件中读入字符串和整数

2019年08月28日 ⁄ 综合 ⁄ 共 1665字 ⁄ 字号 评论关闭

想平时写 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;
}

抱歉!评论已关闭.