MatrixFile.java (1594B)
1 import java.io.File; 2 import java.io.FileNotFoundException; 3 import java.util.Scanner; 4 import java.util.regex.Matcher; 5 import java.util.regex.Pattern; 6 7 public class MatrixFile { 8 File mFile; 9 Scanner fileReader; 10 Matrix matrixRead; 11 Pattern pattern; 12 Matcher matcher; 13 14 public MatrixFile(String filename){ 15 this.mFile = new File(filename); 16 pattern = Pattern.compile("(\\d)x(\\d)"); 17 try { 18 int rows = 0; int cols = 0; 19 this.fileReader = new Scanner(this.mFile); 20 String line = fileReader.nextLine(); 21 matcher = pattern.matcher(line); 22 if (matcher.matches()){ 23 rows = Integer.parseInt(matcher.group(1)); 24 cols = Integer.parseInt(matcher.group(2)); 25 } else { 26 throw new Exception("Matrix in wrong format"); 27 } 28 this.matrixRead = new Matrix(rows, cols); 29 String newValue; 30 for (int r = 0; r < rows; r++) { 31 for (int c = 0; c < rows; c++) { 32 if ((newValue = fileReader.next()) != null){ 33 this.matrixRead.set(r, c, Double.parseDouble(newValue)); 34 } else { 35 throw new Exception("Matrix in wrong format"); 36 } 37 } 38 } 39 40 41 } 42 catch (FileNotFoundException e){ 43 e.printStackTrace(); 44 } 45 catch (Exception e){ 46 e.printStackTrace(); 47 } 48 } 49 50 public Matrix getMatrix(){ 51 return this.matrixRead; 52 } 53 54 }