文件读写和拷贝
程序员文章站
2024-03-21 19:11:52
...
package com.wondream.myframework.app.basictest.io;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
import org.springframework.util.ResourceUtils;
import sun.security.util.ArrayUtil;
import java.io.*;
import java.util.Arrays;
public class FileUtilsTest {
Log logger = LogFactory.getLog(FileUtilsTest.class);
@Test
public void excute(){
try {
File file = ResourceUtils.getFile("classpath:application.properties");
byte[] data = loadBytes(file);
if(data==null){
logger.info("没有读取到任何数据");
return;
}
logger.info(new String(data, "UTF-8"));
File dest = new File("./logs/data.txt");
writeBytes(dest, data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Test
public void copyTest(){
try{
File source = new File("./logs/data.zip");
File dest = new File("./logs/copyData.zip");
copyFile(source, dest);
} catch (Exception e){
}
}
public byte[] loadBytes(File file){
FileInputStream fileInputStream = null;
byte[] data;
try {
fileInputStream = new FileInputStream(file);
data = new byte[fileInputStream.available()];
fileInputStream.read(data);
return data;
} catch (Exception e){
} finally {
try {
if(fileInputStream!=null){
fileInputStream.close();
fileInputStream = null;
}
} catch (Exception e){}
}
return null;
}
public void writeBytes(File file, byte[] data){
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data);
} catch (Exception e){
} finally {
try {
if(fileOutputStream!=null){
fileOutputStream.close();
fileOutputStream = null;
}
} catch (Exception e){}
}
}
public void copyFile(File source, File dest){
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(source);
fileOutputStream = new FileOutputStream(dest);
byte[] buffer = new byte[1024*100];
int total = -1;
while((total = fileInputStream.read(buffer))!=-1){
fileOutputStream.write(buffer, 0, total);
total = -1;
}
} catch (Exception e){
e.printStackTrace();
} finally {
try {
if(fileInputStream!=null){
fileInputStream.close();
fileInputStream = null;
}
if(fileOutputStream!=null){
fileOutputStream.close();
fileOutputStream = null;
}
} catch (Exception e){
}
}
}
}