1.字节输入输出流
- 字节输出流:超类OutputStream,对文件的输出流使用子类FileOutputStream
- 字节输入流:超类InputStream,对文件的输入流使用FileInputStream
- 输入输出字节流操作原理,每次只会操作一个字节(从文件中读取或写入)
实例
- 新建一个File类
File file = new File("filepath");
- 写入文件
OutputStream out = new FileOutputStream(file,true);//append为true表示追加内容
//2.输出的内容
String info = "字节输入输出流\n";
//System.getProperty("line.separator"); //获取换行符
/3.把内容写入到文件
out.write(info.getBytes());
//4.关闭流
out.close();
注意:通过字节输出流写入文件时,一定要将字符串转换成字节数组
- 读取文件
InputStream in = new FileInputStream(file);
//输入
byte[] bytes = new byte[32];
StringBuilder buf = new StringBuilder();
int len=-1;//表示每次读取的字节长度
//把数据读入到数组中,并返回读取的字节数,当不等于-1时,表示读到数据,等于-1表示文件已经读完
while((len=in.read(bytes))!=-1) {
//根据读取到到的字节数组,再转换成字符串内容,再添加到StringBuilder中
buf.append(new String(bytes));
}
//输出内容
System.out.println(buf.toString());
//关闭输入流
in.close();
注意:由于中文可能占多个字节,所以我们每次读取的是候从0到len才是一个完整字符
2.字符输入输出流
- 字符流(字符流 = 字节流 + 解码)
- 字符流:读二进制文件,会自动解码成我们能看懂的字符
字符输入流
- Reader:抽象类,所有字符输入流的超类。
- FileReader:文件字符输入流,读取字符串
实例:读取文件
try {
Reader reader = new FileReader(file);
char[] c = new char[1024];
int len = -1;
while((len=reader.read(c))!=-1) {
System.out.println(new String(c, 0, len));
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
字符输出流
- Write:抽象类,所有字符输出流的超类。
- FileWrite:文件数据的输出字符流
实例:写入文件
try {
Writer writer = new FileWriter(file);
writer.write("我爱你");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
3 . 复制文件实例
从一个输入流中读取数据,然后通过一个输入流写入目标位置
private static void copy(String src, String target) {
File srcFile = new File(src);
File targetFile = new File(target);
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(srcFile);
out = new FileOutputStream(targetFile);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
}
//还有catch和关闭流没有传上来
}
4. 字节字符转换流
- OutputStreamWriter: 可以将输出的字符流转换为字节流的输出形式
- InputStreamReader: 将输入的字节流转换为字符流输入形式
实例:
private static void write(OutputStream out) {
Writer writer = new OutputStreamWriter(out,Charset.defaultCharset());
try {
writer.write("哈哈哈哈哈");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void read(InputStream in) {
Reader reader = new InputStreamReader(in, Charset.defaultCharset());
char[] cs = new char[1024];
int len = -1;
try {
while((len=reader.read(cs))!=-1) {
System.out.println(new String(cs,0,len));
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException {
InputStream in = new FileInputStream("path");
read(in);
// OutputStream out = new FileOutputStream("path");
// write(out);
}