码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-14 22:43:02      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   sp   for   java   on   

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

给自己写个 Java 的。。bubuko.com,布布扣

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


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

标签:blog   http   io   ar   os   sp   for   java   on   

原文地址:http://blog.csdn.net/scnu_jiechao/article/details/41930795

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!