編一程式,統計硬碟上某一文本檔案(例如d:\test.txt)中所包含的字母、數字、和其他字符的個數,并把這些個數資訊寫到一新的文本檔案中。
uj5u.com熱心網友回復:
供樓主參考
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class Count {
public static void main(String[] args) {
Count count = new Count();
String str = count.readFile("D://read.txt");//讀
count.writeFile("D://write.txt",str);//寫
}
private void writeFile(String filePath,String str) {
FileWriter fw;
try {
fw = new FileWriter(filePath);
fw.write(str);
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String readFile(String fileName){
int zm = 0;
int sz = 0;
int other = 0;
try {
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(fileName);
byte[] buff = new byte[1024];
while(fis.available()>0){
int len = fis.read(buff);
String s = new String(buff,0,len);
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(Character.isUpperCase(c) || Character.isLowerCase(c)){
zm++;
}else if(Character.isDigit(c)){
sz++;
} else {
other++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "字母:"+zm+" "+"\n數字:"+sz+" "+"\n其他字符:"+other;
}
}
uj5u.com熱心網友回復:
搜百度吧,使用檔案輸入輸出流操作檔案轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/46166.html
標籤:Java SE
上一篇:SpringBoot 啟動后輸入地址后臺報: Initializing Spring FrameworkServlet 'dispatcherServlet'
