之前看到几个迅雷的上机题,于是在空闲之余写了一个简单的测试:(代码测试通过,如果需要应用到时间项目中需要对异常处理进行处理,也仅代表个人观点,仅供参考,欢迎大家提出更优解决方案)
// 统计文件中指定字符出现个数和位置以及在文件中的行数
BufferedReader in = null;
int count = 0;
int line = 0;
try{
File f = new File("E:\\ftp.txt");
in = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String readLine = null;
String searchStr = "java";
while((readLine = in.readLine()) != null){
++ line;
int position = readLine.indexOf(searchStr);
if(position != -1){
++ count;
System.out.println(readLine + "\t\t文件第 " + line + "行\t\t偏移量:" + position);
}
}
System.out.println("\n字符串出现次数:" + count);
}catch(FileNotFoundException e){
}catch(IOException ex){
}finally{
try{
if(in != null)
in.close();
}catch(Exception exx){}
}
// 统计文件中的字符、数字、空格、以及其它字符
int digit = 0;
int whiteSpace = 0;
int letter = 0;
int another = 0;
BufferedReader in = null;
try{
// DataInputStream in = new DataInputStream(new FileInputStream(new File("E:\\ftp.txt")));
in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\ftp.txt"))));
String readLine = null;
while((readLine = in.readLine()) != null){
// Character ch = new Character(c);
char c ;
for(int i=0;i<readLine.length();i++){
c = readLine.charAt(i);
if(Character.isDigit(c))
++ digit;
else if(Character.isLetter(c))
++ letter;
else if(Character.isWhitespace(c))
++ whiteSpace;
else
++ another;
}
}
System.out.println("数字个数:" + digit + "\n字符个数:" + letter + "\n空格个数:" + whiteSpace + "\n其它字符:" + another);
}catch(FileNotFoundException ex){
System.out.println("ex:" +ex.getMessage());
}catch(IOException e){
System.out.println("e:" + e.getMessage());
}finally{
try{
if(in != null)
in.close();
}catch(Exception exx){}
}