JAVA怎样从txt文件中读入数据到相应类型的数组
数据格式如下:
年份 吉安 峡江 桑庄 寨头
5 4
80 101.5 121.8 227.2 110
79 81.9 101.5 72.4 106
78 59.5 70.4 41.3 59.7
77 79 76.9 85.1 148.6
写的程序如下,抛出异常
[code=Java][/code]
import java.io.*;
public class analysis {
public static void main(String[] args){
String path=null;
String s1;
String s2[];
int m,n;
Double array[][];
FileReader in=null;
BufferedReader input=null;
path="D:\\JavaProject\\analysis\\src\\Data.txt";
try{
in=new FileReader(path);
input=new BufferedReader(in);
}
catch(
FileNotFoundException e1){
System.out.println("");
System.exit(-1);
}
try{
s1=input.readLine();
s2=s1.split(" ", 0);
for(int i=0;i<s2.length;i++){
System.out.println(s2[i]);
}
s1=input.readLine();
s2=s1.split(" ", 0);
m=Integer.valueOf(s2[0]);
n=Integer.valueOf(s2[1]);
array=new Double[n][m];
for(int i=0;i<n;i++){
s1=input.readLine();
s2=s1.split(" ", 0);
for(int j=0;i<s2.length;i++){
array[i][j]=Double.valueOf(s2[j]);
System.out.println(array[i][j]);
}
}
input.close();
in.close();
}
catch(
IOException e2){
System.out.println("");
System.exit(-1);
}
}
}
运行结果:
年份 吉安 峡江 桑庄 寨头
Exception in thread "main"
java.lang.NumberFormatException: For input string: ""
at
java.lang.NumberFormatException.forInputString(
NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.valueOf(Integer.java:582)
at analysis.main(analysis.java:29)
------解决方案--------------------中间有多个连续的空格吧?
------解决方案--------------------[code=Java][/code]import java.io.*;
public class analysis {
public static void main(String[] args) {
String path = null;
String s1;
String s2[];
int m, n;
Double array[][];
FileReader in = null;
BufferedReader input = null;
try {
in = new FileReader("Data.txt");
input = new BufferedReader(in);
} catch (File
NotFoundException e1) {
System.out.println("");
System.exit(-1);
}
try {
s1 = input.readLine();
s2 = s1.split(" ", 0);
for (int i = 0; i < s2.length; i++) {
System.out.println(s2[i]);
}
s1 = input.readLine();
s2 = s1.split(" ", 0);
m = Integer.valueOf(s2[0]);//m列
n = Integer.valueOf(s2[1]);//n行
System.out.println("m="+m+" "+"n="+n);
array = new Double[n][m];
for (int i = 0; i < n; i++) {
s1 = input.readLine();
s2 = s1.split(" ", 0);
for (int j = 0; j < s2.length; j++) {
array[i][j] = Double.valueOf(s2[j]);
System.out.print(array[i][j]+" ");
}
System.out.println();
}
input.close();
in.close();
} catch (IOException e2) {
System.out.println("");
System.exit(-1);
}
}
}
txt文档中数据之间只需一个空格
------解决方案--------------------