自己總結一下Java文件的讀取類似數組數據的方法,自己可以快速查看。
一、規整化數據:
對於數組數據是一一對應的情況
ArrayList<String> arrayList = new ArrayList<>(); try { File file = new File(path); InputStreamReader input = new InputStreamReader(new FileInputStream(file)); BufferedReader bf = new BufferedReader(input); // 按行讀取字符串
String str; while ((str = bf.readLine()) != null) { arrayList.add(str); } bf.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } // 對ArrayList中存儲的字符串進行處理
int length = arrayList.size(); int width = arrayList.get(0).split(" ").length; int array[][] = new int[length][width]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { String s = arrayList.get(i).split(" ")[j]; array[i][j] = Integer.parseInt(s); } } for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { System.out.print(array[i][j] + " "); } System.out.println(); }
二、非規整化數據:
private static void file(String fileName) throws Exception { int array[][] = new int[1024][1024]; File file = new File(fileName); Scanner sc = new Scanner(file); String[] odd = new String[40]; // 奇數行數據
String[] even = new String[40]; // 偶數行數據
int length = 0; int column = 0; int rows = 1; while (sc.hasNextLine()) { if ((rows % 2) == 1) { // 奇數行
odd = sc.nextLine().split("\\s{1,}"); // split("\\2{1,}");不論字符中間有多少個空格都當作一個空格處理
for (int i = 0; i < odd.length-1; i++) { array[length][i] = Integer.parseInt(odd[i]); } } else if ((rows % 2) == 0) { // 偶數行
even = sc.nextLine().split("\\s{1,}"); for (int i = 0; i < even.length-1; i++) { array[length][i] = Integer.parseInt(even[i]); } } if (rows == 2) { column = even.length; } length++; rows++; } sc.close(); for (int i = 0; i < length; i++) { for (int j = 0; j < column; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } }