import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class YcsFileUtils {
public static final int BLOCK = 4 * 1024;
public static void readBytes(String filePath, OutputStream os) {
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
byte[] b = new byte[BLOCK];
int length;
while ((length = fileInputStream.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (IOException e) {
throw new RuntimeException("读取文件的byte数组到输出流失败!filePath = " + filePath + "n" + e);
}
}
public static void writeBytes(byte[] data, String filePath) {
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
outputStream.write(data);
} catch (IOException e) {
throw new RuntimeException("写入byte数组数据到文件中!filePath = " + filePath + "n" + e);
}
}
public static boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
public static String getFileType(String fileName) {
int separatorIndex = fileName.lastIndexOf(File.separator);
if (separatorIndex < 0) {
return "";
}
return fileName.substring(separatorIndex + 1).toLowerCase();
}
public static String getFileExtendName(byte[] photoByte) {
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
return "gif";
}
if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
return "jpg";
}
if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
return "bmp";
}
if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
return "png";
}
throw new RuntimeException("获取文件真实类型失败!");
}
}