怎么编程,谢谢大家,谢谢大家,谢谢大家,谢谢大家
public class Test {
private void readAndCalc() {
String parentFolder = "src/" + getClass().getPackageName().replace('.', '/');
// 源文件路径
String sourceFileName = parentFolder + "/source.txt";
// 输出文件路径
String outputFileName = parentFolder + "/calcCharNum.txt";
File sourceFile = new File(sourceFileName);
if (!sourceFile.exists()) {
return;
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourceFile);
// 读取数据缓存
byte[] bytes = new byte[1024];
// 字符出现次数计数
int[] count = new int[52];
int len;
while ((len = fis.read(bytes)) != -1) {
for (byte b : bytes) {
if (b >= 'A' && b <= 'Z') {
count[b - 'A']++;
}
if (b >= 'a' && b <= 'z') {
count[b - 'a' + 26]++;
}
}
}
fis.close();
fis = null;
// 初始化要输出的文本
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 26; i++) {
stringBuilder.append((char) ('A' + i)).append(':').append(count[i])
.append("\t\t")
.append((char) ('a' + i)).append(':').append(count[i + 26])
.append("\n");
}
byte[] outBytes = stringBuilder.toString().getBytes(StandardCharsets.UTF_8);
// 初始化输出文件
File outputFile = new File(outputFileName);
boolean handRst = outputFile.exists();
if (handRst) {
handRst = outputFile.delete();
}
if (!handRst) {
handRst = outputFile.createNewFile();
}
if (handRst) {
fos = new FileOutputStream(outputFile);
fos.write(outBytes);
fos.close();
fos = null;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test test = new Test();
test.readAndCalc();
}
}
测试输出示例