將讀到的值存成矩陣的類別:
import java.io.*;
public class ReadAsMatrix {
String fileName;
int x,y;
public int[][] readIntFile(String fileName,int x,int y) throws IOException{
this.fileName = fileName;
this.x = x;
this.y = y;
int[][] intgerArry = new int[x][y];
if( new File(fileName).exists()) {
BufferedReader fileInteger = new BufferedReader(new FileReader(fileName));
String line;
int j=0;
while ((line = fileInteger.readLine()) != null) {
String [] unit = line.split("\\s+"); // 用空格分割字串,並指定給字串陣列。
int size = unit.length;
for (int i = 0; i < size; i++){
intgerArry[j][i] = Integer.parseInt(unit[i]);
}
j++;
}
fileInteger.close();
}
else {
System.out.println("沒有 " + fileName + " 登!登!");
}
return intgerArry;
}
}
主程式:
/* 讀寫整數 */
//import java.io.*;
public class Main {
public static void main(String[] args) throws Exception{
// 宣告 rI 是一個讀取檔案值並存為矩陣的物件。
ReadAsMatrix rI = new ReadAsMatrix();
String nameInteger = "整數檔.txt";
int x=10,y=10; // 行數、列數(直行、橫列)。
// 使用 rI 物件的方法,並將結果的矩陣位址傳給 iArry 。
int[][] iArry = rI.readIntFile( nameInteger, x, y);
// 展現讀取的陣列數值。
for ( int j = 0; j < x; j++){
for (int i = 0; i < y; i++){
System.out.print(iArry[j][i]+";");
}
System.out.println();
}
}
}
不看主程式後面展現讀取結果的雙迴圈和註解的話,主程式只用了四行來完成讀取。因為我類別內方法的寫法關係,使用這個程式,x、y 的值必須夠大,太小會出錯,太大則沒有給值的陣列元素會是初始值 0 ,所以如果使我的程式,最好確定檔案的行數與列數。
如果想讀取的是實數、字串,就必須要改變類別中的方法,並不難。我已經寫好了,但示範的程式碼以簡潔為主,就不放上來了。
如果想要對 String.Split 有更多理解,這裡:String.Split。
接下來我想做的練習是統計字母、單字,沒想到網路上已經有人做了,這裡:字的統計。
沒有留言:
張貼留言