注意FileInputStream不能读取文本文件
/*
测试FileInputStream和FileOutputStream的使用
结论:
1.对于文本文件(.txt, .java, .c , .cpp等),使用字符流处理
2.对于非文本文件(.jgp mp3 mp4 avi doc ppt等),使用字节流处理
*/
public class FileInputOutputStreamTest {
@Test
public void testFileInputStream() {
FileInputStream fis = null;
try {
//1.造文件
File file = new File("hello.txt");
//2.造流
fis = new FileInputStream(file);
//3.读数据
byte[] buffer=new byte[5];
int len;//记录每次读取的字节个数
while ((len=fis.read(buffer))!=-1){
String str = new String(buffer, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis!=null){
try {
//4.关闭资源
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
实现对图片的复制
*/
@Test
public void testFileInputOutputStream(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcfile = new File("相关性分析热力图.png");
File destfile = new File("相关性分析热力图1.png");
//
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
//复制过程
byte[] buffer=new byte[5];
int len;
while ((len= fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
} catch (IOException 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();
}
}
}
}
}
指定路径下文件的复制方法
//指定路径下文件的复制
public void copyFile(String srcPath,String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcfile = new File(srcPath);
File destfile = new File(destPath);
//
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
//复制过程
byte[] buffer=new byte[1024];
int len;
while ((len= fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
} catch (IOException 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();
}
}
}
}
@Test
public void testCopytFile(){
long start = System.currentTimeMillis();
String srcPath="02-Python简介.ev4.mp4";
String destPath="py简介";
copyFile(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制花费的时间为:"+(end-start));
}