File分为input和output
文件的读写可以分为字节流读写,字符流读写
分别有缓冲数组读写和缓冲流读写
import java.io.*;
/**
* Created by Administrator on 2017/3/30.
*/
public class FileTest {
public static void main(String[] args) throws IOException {
//copyPicture();
readerTest();
}
//缓冲数组字节流复制图片
public static void copyPicture() throws IOException {
File oriFile = new File("E:\\1.jpg");//需要复制的文件路径
File copyFile = new File("E:\\copy1.jpg");//需要复制到的文件路径
FileInputStream fileInputStream = new FileInputStream(oriFile);//文件的读取通道
FileOutputStream fileOutputStream = new FileOutputStream(copyFile);//文件的写入通道
byte[] buf = new byte[1024];//创建一个缓冲数组用来暂时读取数据字节流
int length = 0;
while ((length = fileInputStream.read(buf)) != -1){
fileOutputStream.write(buf,0,length);
}
fileOutputStream.close();//关闭数据流
fileInputStream.close();
}
//采用缓冲字符流读取文本
/*
演示一下正确的IO异常的处理
*/
public static void readerTest() throws IOException {
BufferedReader bufferedReader = null;
try {
File file = new File("E:\\test.txt");
FileReader fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String content = null;
while ((content = bufferedReader.readLine()) != null){
System.out.println(content);
}
}catch (IOException e){
System.out.println("读取文件资源出错");
throw new RuntimeException(e);
}finally {
try {
if(bufferedReader != null){
bufferedReader.close();
System.out.println("关闭资源文件成功");
}
}catch (IOException e){
System.out.println("关闭资源文件失败");
throw new RuntimeException(e);
}
}
}
}