package test1;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class buffer {
@Test
public void bufferReder() {
FileReader fileReader = null;
FileWriter fileWriter = null;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
fileReader = new FileReader(new File("D://test3.txt"));
fileWriter = new FileWriter(new File("D://test33.txt"));
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
char[] cbuf = new char[5];
int len;
while ((len = bufferedReader.read(cbuf)) != -1) {
bufferedWriter.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//综合练习:读取一个文档中的所有字符出现的次数
@Test
public void Test() {
FileReader fileReader = null;
FileWriter fileWriter = null;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
fileReader = new FileReader(new File("D://十不准.docx"));
fileWriter = new FileWriter(new File("D://统计十不准.docx"));
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
Map<Character,Integer> map = new HashMap<>();
int c = 0;
while ((c = bufferedReader.read())!=-1){
char ch = (char)c;
if(map.get(ch)==null){
map.put(ch,1);
}else{
map.put(ch,map.get(ch)+1);
}
}
Set<Map.Entry<Character,Integer>> entries = map.entrySet();
for (Map.Entry<Character,Integer> enty:
entries) {
switch (enty.getKey()){
case ' ':
bufferedWriter.write("空格="+enty.getValue());
break;
case '\t':
bufferedWriter.write("Tap键盘="+enty.getValue());
break;
case '\n':
bufferedWriter.write("换行符="+enty.getValue());
break;
case '\r':
bufferedWriter.write("回车="+enty.getValue());
break;
default:
bufferedWriter.write(enty.getKey()+"="+enty.getValue());
break;
}
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}