这里写自定义目录标题
Java.io
Java.io中主要有四大抽象类,两种字符类(InputStream/OutputStream),两种字节类(Reader/Writer)
一、InputStream、OutputStream(字节流)
//读取文件(字节流)
InputStream in = new FileInputStream("d:/1.txt");
//写入相应的文件
OutputStream out = new FileOutputStream("d:/2.txt");
//读取数据
//一次性取多少字节
byte[] bytes = new byte[2048];
//接受读取的内容(n代表每次读取的长度)
int n = -1;
//循环取出数据
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//转换成字符串
String str = new String(bytes,0,n,"GBK"); #这里可以实现字节到字符串的转换,比较实用
System.out.println(str);
//写入相关文件
out.write(bytes, 0, n);
}
//关闭流
in.close();
out.close();
二、BufferedInputStream、BufferedOutputStream(缓存字节流)使用方式和字节流类似,但是效率更高
//读取文件(缓存字节流)
BufferedInputStream in = new BufferedInputStream(new FileInputStream("d:/1.txt"));
//写入相应的文件
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:/2.txt"));
//读取数据
//一次性取多少字节
byte[] bytes = new byte[2048];
//接受读取的内容(n代表的每次读取到的数据长度)
int n = -1;
//循环取出数据
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//转换成字符串
String str = new String(bytes,0,n,"GBK");
System.out.println(str);
//写入相关文件
out.write(bytes, 0, n);
}
//清除缓存
out.flush();
//关闭流
in.close();
out.close();
三、InputStreamReader、OutputStreamWriter(字节流,这种方式不建议使用,不能直接字节长度读写)
//读取文件(字节流)
InputStreamReader in = new InputStreamReader(new FileInputStream("d:/1.txt"),"GBK");
//写入相应的文件
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("d:/2.txt"));
//读取数据
//循环取出数据
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read()) != -1) {
System.out.println(len);
//写入相关文件
out.write(len);
}
//清除缓存
out.flush();
//关闭流
in.close();
out.close();
四、BufferedReader、BufferedWriter(缓存流,提供readLine方法读取一行文本
//读取文件(字符流)
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("d:/1.txt"),"GBK"));#这里主要是涉及中文
//BufferedReader in = new BufferedReader(new FileReader("d:/1.txt")));
//写入相应的文件
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/2.txt"),"GBK"));
//BufferedWriter out = new BufferedWriter(new FileWriter("d:/2.txt"));
//读取数据
//循环取出数据
String str = null;
while ((str = in.readLine()) != null) {
System.out.println(str);
//写入相关文件
out.write(str);
out.newLine();
}
//清除缓存
out.flush();
//关闭流
in.close();
out.close();
五、Reader、PrintWriter(PrintWriter很好用,在写数据的同时可以格式化)
//读取文件(字节流)
Reader in = new InputStreamReader(new FileInputStream("d:/1.txt"),"GBK");
//写入相应的文件
PrintWriter out = new PrintWriter(new FileWriter("d:/2.txt"));
//读取数据
//循环取出数据
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read()) != -1) {
System.out.println(len);
//写入相关文件
out.write(len);
}
//清除缓存
out.flush();
//关闭流
in.close();
out.close();