FileInputStream 优化
package com.lichennan.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest02 {
public static void main(String[] args) {
FileInputStream fis =null;
try {
fis = new FileInputStream("E:\\学习\\Java\\LiChennan\\src\\com\\lichennan\\io\\tempfile");
byte[] bytes = new byte[4];
try {
int readcount = 0;
while ((readcount = fis.read(bytes))!=-1){
System.out.print(new String(bytes,0,readcount));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FileOutputStream
package com.lichennan.io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest03 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("myfile",true);
byte[] bytes = {97,98,99,100};
fos.write(bytes);
fos.write(bytes,0,2);
String s = "你是憨憨";
byte[] bs = s.getBytes();
fos.write(bs);
try {
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
文件的复制
package com.lichennan.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Copy01 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E:\\学习\\Java\\笔记\\Java学习路线.pdf");
fos = new FileOutputStream("D:\\Java学习路线.pdf");
byte[] bytes = new byte[1024*1024];
int readCount = 0;
try {
while ((readCount = fis.read(bytes))!=-1){
fos.write(bytes,0,readCount);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}