IO概述
IO的分类
使用IO的规范
字节流
FileInputStream
OutPutStream
FileOutputStream
实现文件的复制
文件拷贝效率提升
以第二种方法实现文件的复制示范;
File file1 = new File("D:\\hi.txt");
File file2 = new File("E:\\hi.txt");
FileOutputStream fos = new FileOutputStream(file1, true);
FileInputStream fis = new FileInputStream(file2);
byte[] by = new byte[1024];
// int ii=fis.read(by);
int len = fis.read(by);
while (len != -1) {
fos.write(by,0,len);
len = fis.read();
}
fos.close();
fis.close();
InputStream类型中read()方法和read(byte[] arr)方法的比较
高效缓冲流
输出流中的close()和flush()的区别
小练习1
//获取一个文本上每个字符出现的次数,将结果写在times.txt上
TreeMap<Character, Integer> map = new TreeMap<>();
BufferedReader br = new BufferedReader(new FileReader("D://hi" + ".txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("D://zuoye1.txt"));
int len = br.read();
while (len != -1) {
char c = (char) len;
map.put(c, !map.containsKey(c) ? 1 : map.get(c) + 1);
len = br.read();
}
br.close();
Set<Character> set = map.keySet();
Iterator<Character> iter = set.iterator();
while (iter.hasNext()) {
Character c = iter.next();
String str = " " + c + " " + map.get(c);
bw.write(str);
}
bw.close();
小练习2
/*用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you must come to the school to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2
//........
(3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)*/
TreeMap<String, Integer> map = new TreeMap<>();
String str = "If you want to change your fate I think you must " + "come to the ujiuye to learn java If If";
BufferedOutputStream bos = null;
//BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("D:\\zuoye3.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] s = str.split(" ");
for (String ss : s) {
map.put(ss, !map.containsKey(ss) ? 1 : map.get(ss) + 1);
}
System.out.println(map);
Set<String> set = map.keySet();
Iterator<String> iter = set.iterator();
while (iter.hasNext()) {
String s1 = iter.next();
String s2 = s1 + " " + map.get(s1) + " 个";
bos.write(s2.getBytes());
bos.write("\r\n".getBytes());
}
bos.close();
小练习3
/*产生10个1-100的随机数,并放到一个数组中
(1)把数组中大于等于10的数字放到一个list集合中,并打印到控制台。
(2)把数组中的数字放到当前文件夹的number.txt文件中*/
ArrayList list = new ArrayList();
int i = (int) (Math.random() * 100);
int[] num = new int[10];
for (int j = 0; j < num.length; j++) {
i = (int) (Math.random() * 100);
if (i >= 10 && i != 0) {
num[j] = i;
}
}
//System.out.println(Arrays.toString(num));
for (int j = 0; j < num.length; j++) {
if (num[j] != 0) {
list.add(num[j]);
}
}
//System.out.println(list);
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("D:\\zuoye4.txt"));
Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
String str = iter.next() + " ";
bos.write(str.getBytes());
bos.write("\r\n".getBytes());
}
} catch (java.io.IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}