File:file就是指一个文件或文件夹,文件及文件夹的创建、删除需要用到它,可以通过他获取文件的各种信息,但是不能获取文件的内容!!要获取文件的内容需要用到其他的类。
FileInputStream,FileOutputStream 字节流(效率太低)
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream("F:\\图片\\截图.png");
fos=new FileOutputStream("F:\\其他\\aa.png");
byte[] b=new byte[1024*3];
int length=0;
try {
while (((length=fis.read(b))!=-1)){
fos.write(b,0,length);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedInputStream BufferedOutputStream
缓冲字节流是为高效率而设计的,真正的读写操作还是靠FileOutputStream
和FileInputStream
,所以其构造方法入参是这两个类的对象也就不奇怪了。
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
fis=new FileInputStream("F:\\图片\\type_back.jpg");
fos=new FileOutputStream("F:\\其他\\type_back.JPG");
bis=new BufferedInputStream(fis);
bos=new BufferedOutputStream(fos);
byte[] b=new byte[1024*30];
int length=0;
try {
while (((length=bis.read(b))!=-1)){
bos.write(b,0,length);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedReader BufferedWriter 简化字符流的读写,new FileWriter
等同于new OutputStreamWriter(new FileOutputStream(file, true))
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
try {
br=new BufferedReader(new FileReader(new File("f:\\图片\\笔记.txt")));
bw = new BufferedWriter(new FileWriter(new File("f:\\其他\\1.txt")));
String temp = "";
while ((temp = br.readLine()) != null) {
bw.write(temp);
bw.newLine();
}
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}