文件的内容类似于:
raw.txt
2 1 4 2 3 3 3 15 3
2 3 4 3 3 3 3 10 2
3 1 4 3 3 3 2 10 3
2 1 3 3 3 1 2 15 3
2 2 4 3 3 3 3 10 3
3 1 3 2 3 3 1 15 2
2 1 4 3 3 3 2 05 2
源程序:
package getdataformfile;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class GetData {
public GetData() {
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String FILE_NAME = "d://我的文档//桌面//test//raw.txt"; //绝对路径
GetData getData = new GetData();
List list = getData.readFile(FILE_NAME);
int[][] endArray = getData.getArray(list);
getData.displayResult(endArray);
}
/*
*
* 显示整型数组
*
* */
private void displayResult(int[][] intArray) {
System.out.println(
"=======================Result=============================");
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray[i].length; j++) {
System.out.print(intArray[i][j] + "/t");
}
System.out.println("/n");
}
}
/*
*
* 将字符列表转换成整型数组
*
* */
@SuppressWarnings("unchecked")
private int[][] getArray(List list) {
int[][] intArray = null;
if (list == null) {
return null;
}
intArray = new int[list.size()][];
String tempString = "";
int count = 0;
String[] tempArray = null;
for (int i = 0; i < list.size(); i++) {
tempString = list.get(i).toString().trim();
if (tempString == null || tempString.length() <= 0) {
continue;
}
tempArray = tempString.split(" "); //用空格区分每个数字
count = 0;
for (int j = 0; j < tempArray.length; j++) {
if (tempArray[j] == null ||
tempArray[j].trim().length() <= 0 ||
this.isNumeric(tempArray[j])) {
continue;
}
count++;
}
intArray[i] = new int[count];
count = 0;
for (int j = 0; j < tempArray.length; j++) {
if (tempArray[j] == null ||
tempArray[j].trim().length() <= 0 ||
this.isNumeric(tempArray[j])) {
continue;
}
intArray[i][count] = Integer.parseInt(tempArray[j]);
count++;
}
}
return intArray;
}
/*
*
* 将文件中的字符串对到List中
*
*/
@SuppressWarnings("unchecked")
private List readFile(String fileName) {
List
list = new ArrayList
();
File file = new File(fileName);
if (!file.exists()) {
return list;
}
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(fileReader);
String temp = "";
for (temp = bufferReader.readLine();
temp != null;
temp = bufferReader.readLine()) {
if (temp.trim().length() > 0) {
list.add(temp);
}
}
bufferReader.close();
fileReader.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return list;
}
/*
*
* 判断是否是数字
*
*/
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return true;
}
return false;
}
}