日期:2014-05-20 浏览次数:20744 次
package acme2; /** *http://stackoverflow.com/questions/285712/java-reading-a-file-into-an-array * @author Bing */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileArrayProvider { //reference website: //http://stackoverflow.com/questions/1855753/reading-double-values-from-a-file public int i, j; public Double[][] myArray = null; public void readLines(String filename) throws IOException { //public String[] readLines(String filename) throws IOException { FileReader fileReader = new FileReader(filename); BufferedReader bufferedReader = new BufferedReader(fileReader); List<String> lines = new ArrayList<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } bufferedReader.close(); System.out.println(lines.size()); //lines.size()=245880 myArray = new Double[lines.size()/6][6]; int index = 0; for( i = 0; i < (lines.size()/6); i++){ for( j = 0; j < 6; j++){ myArray[i][j] = lines.get(index) ; [b]/*Double.parseDouble(lines.get(index)) ; *Double.valueOf(s).doubleValue(); *问题出在这个二维数组上。原本lines是个string list,现在想把所有的内容读入到类型为double的二位数组myarray里, 尝试了网上提到的几个转换方式都没成功。谁还有好办法啊?谢谢啦 */ [/b] index++; System.out.println(myArray[i][j]); } } } }
int cnt = lines.size()%6 == 0 ? lines.size()/6 : lines.size()/6 + 1; myArray = new Double[cnt][6]; int index = 0; for( i = 0; i < myArray.length; i++){ for( j = 0; j < 6; j++){ if (index < lines.size()) { //避免越界 if (lines.get(index).matches("\\d+([.]\\d+)?")) { myArray[i][j] = Double.valueOf(lines.get(index)); } else { System.out.printf("error double[%s]\n", lines.get(index)); myArray[i][j] = 0.0; } System.out.println(myArray[i][j]); } else { break; } index++; } }
------解决方案--------------------
你的一行数据是3.04134 0.677819 11.4217 5.72507 4.59348 4.00403,怎么能转成Double呢
要分割以后转换,即把3.04134转换,0.677819转换,等等,而不是直接整行转换。
myArray = new Double[lines.size()][6]; //既然一行是6个数据,就不要size()/6了 for( i = 0; i < myArray.length; i++){ String data[] = lines.get(i).split("\\s+"); //分割 for( j = 0; j < 6; j++){ if (j < data.length) { //避免越界 if (data[j].matches("\\d+([.]\\d+)?")) { myArray[i][j] = Double.valueOf(); } else { System.out.printf("error double[%s]\n", data[j]); myArray[i][j] = 0.0; } System.out.println(myArray[i][j]); } else { myArray[i][j] = 0.0; //补齐6个数据,缺省为0,LZ可以根据需求而改变 } } }