缓冲流的原理
字节缓冲输出流
public class Buffer {
public static void main(String[] args) throws IOException {
FileOutputStream fops = new FileOutputStream("F:\\test\\aa.txt");
BufferedOutputStream bops = new BufferedOutputStream(fops);
bops.write("小新妮妮风间".getBytes());
bops.flush();
}
}
字节缓冲输入流
public class BufferIps {
public static void main(String[] args) throws IOException {
FileInputStream fips = new FileInputStream("K:\\aa\\cc.txt");
BufferedInputStream bips = new BufferedInputStream(fips);
int len = 0;
while((len = bips.read()) != -1) {
System.out.println(len);
}
bips.close(); //自动关闭fips
}
}
public class BufferIps {
public static void main(String[] args) throws IOException {
FileInputStream fips = new FileInputStream("F:\\test\\aa.txt");
BufferedInputStream bips = new BufferedInputStream(fips);
byte[] bytes = new byte[1024];
int len = 0;
while((len = bips.read(bytes)) != -1) {
System.out.println(new String(bytes,0,len));
}
}
}
字符缓冲输出流
public class BufferedWriterC {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("F:\\test\\aa.txt");
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < 10; i++) {
bw.write("小新妮妮风间");
bw.newLine();
}
bw.flush();
bw.close();
}
}
ps:弄了半天代码报错,问题就是命名橙BufferedWritter了,算是个教训
字符缓冲输入流
public class BufferedReaderC {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("F:\\test\\aa.txt"));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
练习:对文本的内容进行排序
public class PracticeSort {
public static void main(String[] args) throws IOException {
HashMap<String,String> mapString = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader("F:\\test\\aa.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\test\\bb.txt"));
String line;
while((line = br.readLine()) != null) {
String[] split = line.split("\\.");
mapString.put(split[0],split[1]);
}
for (String key : mapString.keySet()) {
String value = mapString.get(key);
line = key + "." + value;
bw.write(line);
bw.newLine();
}
bw.close();
br.close();
}
}
感觉前面的map的方法都有些模糊了。。