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



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com