java学习第18天--IO

统计一个字符串中每个字符出现的次数 :
aaabbbccdde
结果要求格式如下 :
a(3)b(3)c(2)d(2)e(1)
改进为键盘录入字符串

package com.czz.work;
 
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
 
/*
 * 统计一个字符串中每个字符出现的次数 :
ccddea aa bbb
结果要求格式如下 :
a(3)b(3)c(2)d(2)e(1)
 */

public class test01 {
 
   public static void main(String[] args ) {
      // 创建 treemap 对象
      TreeMap<Character, Integer> tm = new TreeMap<>();
     
   /* // 初始化字符串
      String str = " ccddeaaabbb ";*/
     
      // 改为键盘录入字符串
      Scanner sc = new Scanner(System. in );
      System. out .println( "input a string: " );
      String s = sc .nextLine();
     
      // 将字符串转换为字符数组
      char [] chs = s .toCharArray();
     
      // 循环遍历字符数组 , 取出数组
      for ( int i = 0; i < chs . length ; i ++) {
         char ch = chs [ i ];
        
         // 判断是否是第一次出现
         if (! tm .containsKey( ch )) {
            tm .put( ch , 1);
         } else {
            // 取出原 value,+1 再放回
            Integer value = tm .get( ch );
            tm .put( ch , value +1);
         }
      }
     
      System. out .println( tm );
     
      // 创建 StringBuffer 空对象
      StringBuffer sb = new StringBuffer();
     
      // map 进行遍历
      Set<Character> keys = tm .keySet();
      for (Character c : keys ) {
         sb .append( c ). append ( "(" ).append( tm .get( c )). append ( ")" );
      }
      System. out .println( sb .toString());
     
      // 有空格的情况
      System. out .println( sb .toString().replaceAll( " " , " 空格 " ));
   }
}
 

统计一个字符串中每个单词出现的次数 :
this is a cat and that is a mice and where is the food
结果格式如下 :
单词 :a , 次数是 :2
单词 :is, 次数是 :3
package com.czz.fec1;
 
import java.util.HashMap ;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/*
 * 统计一个字符串中每个单词出现的次数 :
this is a cat and that is a mice and where is the food
结果格式如下 :
单词 :a , 次数是 :2
单词 :is, 次数是 :3
 */
public class TestDemo3 {
 
   public static void main(String[] args ) {
      // String s = "this is a cat, and that is a mice, and where is the food?";
      @SuppressWarnings ( "resource" )
      Scanner sc = new Scanner(System. in );
      System. out .println( "input a string:" );
      String s = sc .nextLine();
 
      HashMap <String, Integer> hm = new HashMap <>();
 
      Pattern p = Pattern. compile ( "\\b\\w+\\b" );
      Matcher m = p .matcher( s );
      while ( m .find()) {
         String word = m .group();
         if (! hm .containsKey( word )) {
            hm .put( word , 1);
         } else {
            hm .put( word , hm .get( word ) + 1);
         }
      }
 
      Set<String> keys = hm .keySet();
      for (String word : keys ) {
         System. out .println( " 单词是 : " + word + "\t 次数是 : " + hm .get( word ));
      }
 
/*   
      String[] words = s.split(" +");
      for ( int i = 0; i < words.length; i++) {
         if (!hm.containsKey(words[i])) {
            hm.put(words[i], 1);
         } else {
            hm.put(words[i], hm.get(words[i]) + 1);
         }
      }
 
      Set<String> keys = hm.keySet();
      for (String word : keys) {
         System.out.println(" 单词是 : " + word + "\t 次数是 : " + hm.get(word));
      }
*/    
   }
}
 
IO File文件的基本操作
一、File类简介
File类不但代表文件和目录的双重含义,还表示一个刚新建于内存中尚未同步去硬盘的文件或目录。File类的作用描述了文件本身的属性,包括用来获取或处理与磁盘文件相关的信息,例如大小、权限、生成时间、最后修改时间和目录路径等等。此外,浏览子目录层次结构也是经常做的操作。尽管File类的实例对象并不打开文件,也不提供任何文件内容的处理功能。但是其他java.io包中的类通常都需要使用File对象来指定要操作的文件或目录。
二、注意问题
由于File需要和操作系统的文件打交道,而Window和Linux的文件系统差异性比较大,所以我们首先要先讲解一下两个注意问题:
1、分割符
Unix/Linux在路径名中分隔符是下斜杠“/”(位于键盘的下端),比如:
/usr/java/jdk7/bin/java.bin
在Windows系统中沿用Dos系统使用的路径分隔符上斜杠“\”(位于键盘的上端)。不过Java编程时很快就会发现这样定义字符串路径是行不通的:
String path=”C:\java\jdk\bin\java.exe”; //报错
上斜杠“\”在java中是转移字符的开始标记,因此你需要进行必要的转义操作:
String path=”C:\\java\\jdk\\bin\\java.exe”; //正确
对于上面问题还有很多解决方法,可以统一使用Java约定是用UNIX和URL风格的斜线来作路径分隔符,这样的写法经过测试,在window下面也是可以正常运行的:
String path=”C:/java/jdk/bin/java.exe”; //正确
File类还提供了一个属性 File.separator 代替分隔符,这个也可以解决问题。
2、相对路径和绝对路径
  1. 绝对路径:是window系统中指的是从盘符开始的路径,linux系统中指的是以"/"开头——代表根目录的路。
像一下这些路径就是绝对路径
C:\java\jdk\bin\java.exe
/usr/hello.java
  1. 相对路径,顾名思义,相对路径就是相对于当前文件的路径。相对路径的真实路径要根据当前所在目录决定的,如:当前所在的路径是c:/java,那么路径hello/abc.txt路径就表示在c:/java/hello/abc.txt。相比绝对路径而言,相对路径灵活而且效率更高。相对路径还有两个特殊符号:
"./":代表目前所在的目录。
"../":代表上一层目录。
三、代码示例
1、构造方法 。只需要写上路径,既可以指向文件也可以指向目录。代码如下:
//目录
File path= new File("g:\\java\\abc\\cba\\dfd");
//文件
File file= new File("g:\\java//hello.java");
你可以去相应的目录下,查看是否建立成功。
2、建立目录和文件 。建立目录和创建文件使用方法是不同的,其中建立目录方法有两个: mkdirs mkdir 。mkdir要求父级目录必须存在,否则会建立失败,而mkdirs会建立所有的目录。不管是建立文件还是目录最好都先判断是否有其权限,还得判断原文件是否存在,否则会覆盖原文件。代码如下:
//新建目录和新建文件方法
//System.out.println(path.exists());
if(!path.exists()){
//mk make dir
if(path.mkdirs()){
System.out.println( "建立成功" );
}else{
System.out.println( "建立失败" );
}
}
//新建文件
if(!file.exists()){
try {
file. create NewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
3、其他操作。 我们可以通过File类读取文件的基本属性,还可以删除文件,重命名文件等操作。具体大家可以运行下面代码:
System.out.println("是否可读:"+file.canRead());System.out.println("是否可写:"+file.canWrite());System.out.println("是否可执行:"+file.canExecute());System.out.println("是否是目录:"+path.isDirectory());System.out.println("是否是文件:"+path.isFile());System.out.println("是否隐藏:"+file.isHidden());/System.out.println("删除文件:"+file.delete());System.out.println("删除目录:"+path.delete());System.out.println("获得文件的完整路径:"+file.getAbsolutePath());file.renameTo(new File("d://abc.txt"));//浏览目录File javaFile=new File("g://java");File files[]= javaFile.listFiles();System.out.println("文件名称\t修改时间\t类型\t大小");for(int i=0;i<files.length;i++){File f=files[i];Date date=new Date(f.lastModified());SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");String ftype=f.isDirectory()?"目录":"文件";System.out.println(f.getName()+"\t"+sdf.format(date)+"\t"+ftype+"\t"+f.length());}
四、实例
获取某个盘符下的指定类型的文件信息
例:获取 c 盘下的所有 jpg 图片信息:大小,文件名
package com.czz.fec1;
 
/*
 * 获取某个磁盘下的指定类型的文件信息
 * */
 
import java.io.File;
 
public class TestDemo2 {
 
   static int count = 0;
   public static void main(String[] args ) {
      File folder = new File( "E:\\ 图片 \\ 云台山 " );
     
      File[] files = folder .listFiles();
      for (File file : files ) {
         if ( file .getName().toUpperCase().endsWith( ".JPG" )) {
            count ++;
            System. out .println( " 图片名 : " + file .getName() + "\t 大小为 :" + file .length());
         }
      }
      System. out .println( " 图片总个数为 :" + count );
   }
}
 

批量更改某个文件夹下的文件名
1. 去掉某些标志
2. 添加某些标志
思路:
1. 封装目录成 File 对象
2. 得到此对象下的所有 File 对象数组
3. 遍历数组,并改名
package com.czz.io;
 
/*
 * 批量更改某个文件夹下的文件名
   1. 去掉某些标志
   2. 添加某些标志
        思路:
   1. 封装目录成 File 对象
   2. 得到此对象下的所有 File 对象数组
   3. 遍历数组,并改名
 * */
 
import java.io.File;
 
public class FileDemo4 {
 
   public static void main(String[] args ) {
      // TODO Auto-generated method stub
      File folder = new File( "E:/niling/czz" );
     
      File[] f = folder .listFiles();
     
      // 遍历并批量增加标志
      for (File file : f ) {
         String name = "www.czz.com_" + file .getName();
        
         File file2 = new File( file .getParent(), name );
        
         if ( file .renameTo( file2 )){
            System. out .println( file .getName() + " 改名成功 !" );
            } else {
            System. out .println( file .getName() + " 改名失败 !" );
            }
         }
      }
     
     
      // 遍历并批量改名 , 去掉标志
      /*for (File file : f) {
         if(file.getName().toUpperCase().endsWith(".TXT")) {
            // 得到原文件名
            String name = file.getName();
           
            // 得到新文件名
            int index = name.indexOf("_");//indexOf 表示返回指定字符串所处的索引位置
            String newName = name.substring(index+1);//substring 表示提取索引处的字符
            System.out.println(newName);
           
            // 创建新的 file 对象
            File newFile = new File(file.getParent(), newName);
           
            if(file.renameTo(newFile)) {
                System.out.println(" 改名成功 ");
            }else {
                System.out.println(" 改名失败 ");
            }
         }
      }*/
   }
 
 
 

求5!
package com.czz.fec;
 
import java.util.Scanner;
 
public class FecDemo5 {
 
   public static void main(String[] args ) {
     
      Scanner sc = new Scanner(System. in );
      while ( true ) {
         System. out .println( "Please Input A Num:" );
         int n = sc .nextInt();
         int res = getNum ( n );
         System. out .println( res );
      } 
   }
  
   // 自定义方法
   public static int getNum( int n ) {
      if ( n == 1) {
         return 1;
      } else {
         return n * getNum ( n - 1);
      }
   }
}
 

不死神兔问题
package com.czz.fec;
 
/*
 * 不死神兔问题
1 1
2 1
3 2
4 3
5 5
6 8
...
第二十个月有多少对兔子 ( 假设期间兔子都不死 )
 */
 
public class FecDemo {
 
   public static void main(String[] args ) {
      int month = 20;
      int res = getNum ( month );
      System. out .println( res );
   }
 
   // 自定义递归
   public static int getNum( int month ) {
      if ( month == 1 || month == 2) {
         retu rn 1;
      } else {
         return getNum ( month - 1) + getNum ( month - 2);
      }
   }
}
 

递归查找某个路径下大小超过50M的avi视频
package com.czz.fec;
/*
 * 递归删除大于 50M 的以 . avi 为结尾标志的文件
 * */
import java.io.File;
 
public class FecDemo2 {
 
   static int count =0;  // static, 这样整个类都可以使用
   public static void main(String[] args ) {
      File folder = new File( "F:\\ 大数据 \\ 老男孩大数据学习 \\java 基础视频 " );
      getFolder ( folder );
      System. out .println( " 数目为 :" + count );
   }
  
   public static void getFolder(File folder ) {
      File[] files = folder .listFiles();
      for (File file : files ) {
         if ( file .isFile()) {
            if ( file .getName().toUpperCase().endsWith( ".AVI" )) {
                if (( file .length()/1024/1024) > 50) {
                   count ++;
                   System. out .println( " 文件名 : " + file .getAbsolutePath() + ",\t 大小为 :" + file .length());
                }
            }
         } else {
            getFolder ( file );
         }
      }
   }
}
 
递归删除带内容的文件夹
package com.czz.fec;
 
import java.io.File;
 
/*
 * 递归删除带内容的文件夹
 * */
 
public class FecesDemo4 {
 
   public static void main(String[] args ) {
      File folder = new File( "E:\\niling" );
      delFolder ( folder );
   }
 
   // 自定义删除
   public static void delFolder(File folder ) {
      File[] files = folder .listFiles();
      for (File file : files ) {
         if ( file .isFile()) {
            if ( file .delete()) {
                System. out .println( " 文件 : " + file + " 被成功删除 " );
            } else {
                System. out .println( " 文件 : " + file + " 删除失败 " );
            }
         } else {
            delFolder ( file );
         }
      }
     
      if ( folder .delete()){
         System. out .println( " 文件夹 : " + folder .getName() + " 被成功删除 " );
      } else {
         System. out .println( " 文件夹 : " + folder .getName() + " 删除失败 " );
      }
   }
}
 

统计某个盘符下所有的.class字节码文件的个数
package com.czz.fec;
 
import java.io.File;
 
/*
 * 统计某个盘符下所有的 .class 字节码文件的个数
 * */
 
public class FecesDemo3 {
 
   static int count = 0;
  
   public static void main(String[] args ) {
      File floder = new File( "E:\\Java" );
      getCount ( floder );
      System. out .println( " 总数为 :" + count );
   }
  
   // 自定义递归方法
   public static void getCount(File folder ) {
      File[] files = folder .listFiles();
     
      for (File file : files ) {
         if ( file .isFile()) {
            if ( file .getName().toUpperCase().endsWith( ".CLASS" )) {
                count ++;
                System. out .println( file .getAbsolutePath());
            }
         } else {
            getCount ( file );
         } 
      }
   }
}
 

猜你喜欢

转载自blog.csdn.net/czz1141979570/article/details/80056541