输出一串字符每个字出现的次数。
代码如下:
package chapter9_9;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class QuestionTest {
public static void main(String[] args) {
testCounter();
}
public static void testCounter(){
String str = "*Constructs a new <tt>HashMap</tt> with th 苑苑 e same mappings as the *"+
"嘻嘻 specified <tt>Map</tt>. The <tt>HashMap</tt> is created with "+
"default load factor (0.75) and an initial capacity sufficient to*hold the "+
"mappings in the specified <tt>Map</tt>.";
//把字符串转为数组
char [] charArr = str.toCharArray();
//创建一个map
Map<Character,Integer> counterMap =new HashMap<>();
//遍历数组,得每个字符
for (int i =0;i < charArr.length;i++){
//拿到字符作为key去集合中查找
Integer value = counterMap.get(charArr[i]);
if (value == null){
//把字符作为键,1为值存储到集合
counterMap.put(charArr[i],1);
}else {
//把值加1重写写入集合
value +=1;
counterMap.put(charArr[i],value);
}
}
//遍历输出
Set<Map.Entry<Character,Integer>> entrySet = counterMap.entrySet() ;
for(Map.Entry<Character,Integer> entry: entrySet){
System.out.println(entry.getKey()+"字符出现的次数="+entry.getValue());
}
}
}
拷贝
把文件拷贝到另一个文件。
import java.io.*;
public class BufferMain {
public static void main(String[] args) throws IOException {
//读取文件
FileInputStream fis = new FileInputStream("D:\\fd.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos= new FileOutputStream("D:\\copy.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int size;
byte [] buf = new byte[1024];
while ((size = bis.read(buf))!=-1){
bos.write(buf,0,size);
}
//刷新此缓冲区的输出流,才可以保证数据全部输出完成
//close,关闭时自动刷新
//bos.flush();
bis.close();
bos.close();
}
}
拷贝图片
把一个文件里的图片拷贝并且创建一个文件粘贴到其中
package chapter11_5;
import java.io.*;
public class CapyMain {
public static void main(String[] args) {
//定义路径 //被拷贝文件路径
String dir = "D:\\ny";
//被拷贝文件文件名
File file = new File(dir+"\\image");
//定义这个目录下所有文件
File []files = file.listFiles();
for(File from :files){
String fileName =from.getName();
//拷贝到的文件路径
copy(from.getAbsolutePath(),dir+"\\image2\\"+fileName);
}
}
//主体方法 从哪里来 去哪里
public static void copy(String from,String to){
try{
//判断文件存不存在 //判断上层目录
File targetDir = new File(new File(to).getParent());
//是否存在
if (targetDir.exists()){
//创建多层
targetDir.mkdirs();
}
//文件读写
FileInputStream fis =new FileInputStream(from);
BufferedInputStream bis =new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(to);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int size;
byte [] buf = new byte[1024];
while ((size = bis.read(buf)) !=-1){
bos.write(buf,0,size);
}
bis.close();
bos.close();
}catch (Exception e){
}
}
}