統計某個檔案中出現的字元個數,數字個數,空格個數,總共有多少行?
阿新 • • 發佈:2019-02-15
package com.xmobo.mapp.ofcard.test; import java.io.FileInputStream; public class Test { /** * Get File Infos * * @param path * @return * @throws Exception */ public static String[] getFileInfos(String path) throws Exception { int chacracter = 0; int words = 0; int workspace = 0; int enter = 0; FileInputStream file = new FileInputStream(path); byte[] temp = new byte[1024]; int size = 0; while ((size = file.read(temp)) != -1) { for (int i = 0; i < size; i++) { byte tmp = temp[i]; if ((tmp >= 'a' && tmp <= 'z') || (tmp >= 'A' && tmp <= 'Z')) { chacracter++; } else if (tmp >= '0' && tmp <= '9') { words++; } else if (tmp == ' ') { workspace++; } else if (tmp == '\n') { enter++; } } } file.close(); // {字元,數字,空格,回車} String[] strArray = { String.valueOf(chacracter), String.valueOf(words), String.valueOf(workspace), String.valueOf(enter) }; return strArray; } // main public static void main(String[] args) throws Exception { String path = "config1.xml"; System.out.println(Test.getFileInfos(path)[2]); } }