常规写法
public static long copyFile ( File srcFile, File desFile) throws FileNotFoundException {
Long start = System. currentTimeMillis ( ) ;
if ( ! srcFile. exists ( ) ) {
throw new FileNotFoundException ( "源文件不存在" ) ;
}
if ( ! desFile. getParentFile ( ) . exists ( ) ) {
desFile. getParentFile ( ) . mkdirs ( ) ;
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream ( srcFile) ;
outputStream = new FileOutputStream ( desFile) ;
byte [ ] data = new byte [ 2048 ] ;
int len = 0 ;
do {
len = inputStream. read ( data) ;
if ( len != - 1 ) {
outputStream. write ( data, 0 , len) ;
}
} while ( len != - 1 ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
try {
inputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
outputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
Long end = System. currentTimeMillis ( ) ;
return end - start;
}
进阶
public static long copyFile ( File srcFile, File desFile) throws FileNotFoundException {
Long start = System. currentTimeMillis ( ) ;
if ( ! srcFile. exists ( ) ) {
throw new FileNotFoundException ( "源文件不存在" ) ;
}
if ( ! desFile. getParentFile ( ) . exists ( ) ) {
desFile. getParentFile ( ) . mkdirs ( ) ;
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream ( srcFile) ;
outputStream = new FileOutputStream ( desFile) ;
byte[ ] data = new byte[ 2048 ] ;
int len = 0 ;
while ( ( len = inputStream. read ( data) ) != - 1 ) {
outputStream. write ( data, 0 , len) ;
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
try {
inputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
outputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
Long end = System. currentTimeMillis ( ) ;
return end - start;
}
时代变了再进阶法
public static long copyFile ( File srcFile, File desFile) throws FileNotFoundException {
Long start = System. currentTimeMillis ( ) ;
if ( ! srcFile. exists ( ) ) {
throw new FileNotFoundException ( "源文件不存在" ) ;
}
if ( ! desFile. getParentFile ( ) . exists ( ) ) {
desFile. getParentFile ( ) . mkdirs ( ) ;
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream ( srcFile) ;
outputStream = new FileOutputStream ( desFile) ;
inputStream. transferTo ( outputStream) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
try {
inputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
outputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
Long end = System. currentTimeMillis ( ) ;
return end - start;
}