package com.atrrx.java;
import org.testng.annotations.Test;
import java.io.*;
public class FileInputOutputStreamTest {
//使用字符流FileInputStream处理文本文件,可能出现乱码
@Test
public void testFileInputStream() throws IOException {
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) {
throw new RuntimeException(e);
} finally {
try {
//.4关闭资源
if(fis!=null)
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/*
* 实现对图片的复制操作
*
*
* */
@Test
public void testFileInputOutputStream(){
FileInputStream fis=null;
FileOutputStream fos=null;
try {
//
File srcFile=new File("鞠.jpg");
File destFile=new File("鞠1.jpg");
//
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) {
throw new RuntimeException(e);
} finally {
//
try {
if (fos!=null)
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if (fis!=null)
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//指定路径下的文件的复制
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) {
throw new RuntimeException(e);
} finally {
//
try {
if (fos!=null)
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if (fis!=null)
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Test
public void testCopyFile(){
long start=System.currentTimeMillis();
String srcPath="C:\\Users\\28714\\Desktop\\31.状语从句(一).mp4";
String destPath="C:\\Users\\28714\\Desktop\\31.状语从句2(一).mp4";
// String srcPath="hello.txt";
// String destPath="hello3.txt";
copyFile(srcPath,destPath);
long end=System.currentTimeMillis();
//复制操作花费的时间为:3650(1 秒=1000 毫秒)
System.out.println("复制操作花费的时间为:"+(end-start));//3650
}
}