import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class InputStreamDemo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("PotPlayerSetup64.exe");
FileOutputStream fos = new FileOutputStream("b.exe");
// int data; // 按单个字节读,这种方法反复的要操作磁盘读写操作,因此很慢
// while ((data = fis.read()) != -1) {
// fos.write(data);
// }
// System.out.println("copy finished");
// 这种方法是一次就读满一个byte数组,然后写入,这样将byte数组设置大一点就可以
// 减少读取写入的次数
// byte[] bs = new byte[1024 * 1024];
// int len = -1;
// while ((len = fis.read(bs)) != -1) {
// fos.write(bs, 0, len);
// }
// System.out.println("copy finished");
// 使用bufferedinputstream把fis装进去,这样也能减小磁盘的读写操作次数
// 原理是bis内部会有一个缓冲区,缓冲区的大小为8192个字节,当对bis读取时,
// 首先bis从磁盘获取8192个字节的内容,然后再将读取的字节返回给bis.read
// 这种方法相比于fis.read(byte)来说,当byte数组比较大时,fis.read(byte)
// 会快,因为buffered的读写是要操作两个数组,读一个缓冲区,写也有一个缓冲区
// 而fis.read(byte)只对一个数组进行操作
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
System.out.println("copy finished");
bis.close();
bos.close();
fis.close();
fos.close();
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderDemo {
static String read(String filename) throws IOException {
// FileReader继承了Reader这个类,这个类用于字符流,再在外面加一个
// BufferedReader,其实也是取到一个起到一个缓冲的作用
BufferedReader bReader = new BufferedReader((new FileReader(filename)));
String s = null;
StringBuilder sb = new StringBuilder();
while ((s = bReader.readLine()) != null) {
sb.append(s + '\n');
}
bReader.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.println(read("inputfile.txt"));
}
}