Java IO流 -> 文件字节流
- 以File、Array、String、Piped这类数据源名开头的一般是节点流,直接对接节点数据。
类型 | 字符流 | 字节流 |
---|
File | FileReader FileWriter | FileInputStream FileOutputStream |
Memory Array | CharArrayReader CharArrayWriter | ByteArrayInputStream ByteArrayOutputStream |
Memory String | StringReader StringWriter | —— |
Pipe(管道) | PipedReader PipedWriter | PipedInputStream PipedOutputStream |
1. 文件字节流FileInputStream/FileOutputStream
- FileInputStream:以字节方式读取文件,适合读取所有类型的文件(图像、视频等),全字符(纯文本)可以使用FileReader。
- FileOutputStream : 通过字节方式写出或追加数据到文件,适合所有类型的文件(图像、视频等),全字符(纯文本)可以使用FileWriter。
import java.io.*;
public class TestFileInputStream {
public static void main(String[] args) {
File file = new File("D:\\JavaAno\\code\\JavaSE\\基础语法\\src\\com\\io\\endpoint\\in.txt");
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] buffer = new byte[100];
for(int len = -1; (len = in.read(buffer)) != -1;){
System.out.println(new String(buffer, 0, len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
public class TestFileOutputStream {
public static void main(String[] args) {
File file = new File("out.txt");
OutputStream out = null;
try {
out = new FileOutputStream(file);
byte[] buffer = "This is a new txt".getBytes();
out.write(buffer,0, buffer.length);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(out != null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2. 文件字节流封装FileUtil
import java.io.*;
public class FileUtil {
private InputStream in;
private OutputStream out;
private int size = 1024;
public FileUtil(){
}
public FileUtil(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public void copy(String srcFile, String destFile){
try{
this.in = new FileInputStream(srcFile);
this.out = new FileOutputStream(destFile);
this.copy();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
public void copy(){
if(in == null || out == null){
throw new RuntimeException("输入输出流不可以为空!");
}
try{
byte[] buf = new byte[size];
for(int len = -1; (len = in.read(buf)) != -1; len++){
out.write(buf,0,len);
}
out.flush();
}catch(IOException e){
e.printStackTrace();
}finally {
this.close();
}
}
private void close(){
try{
if(out != null){
out.close();
}
}catch (IOException e){
e.printStackTrace();
}
try{
if(in != null){
in.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}