com.github.dennisit.vplus.data.utils.FileReadUtils Maven / Gradle / Ivy
package com.github.dennisit.vplus.data.utils;
import com.google.common.base.Joiner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class FileReadUtils {
public static String readAll(String fileName) throws IOException {
BufferedReader reader = createLineRead(fileName);
List lines = reader.lines().collect(Collectors.toList());
String content = Joiner.on("\n").join(lines);
return content;
}
public static InputStream createByteRead(String fileName) throws IOException {
return getStreamByFileName(fileName);
}
public static Reader createCharRead(String fileName) throws IOException {
return new InputStreamReader(getStreamByFileName(fileName), Charset.forName("UTF-8"));
}
public static BufferedReader createLineRead(String fileName) throws IOException {
return new BufferedReader(new InputStreamReader(getStreamByFileName(fileName), Charset.forName("UTF-8")));
}
public static InputStream getStreamByFileName(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException("fileName should not be null!");
}
if (fileName.startsWith("http")) { // 网络地址
return FileUtils.openInputStream(new File(fileName));
//return HttpUtils.downFile(fileName);
} else if (fileName.startsWith("/")) { // 绝对路径
Path path = Paths.get(fileName);
return Files.newInputStream(path);
} else { // 相对路径
return FileReadUtils.class.getClassLoader().getResourceAsStream(fileName);
}
}
private static String bytesToHex(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (byte aSrc : src) {
int v = aSrc & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 获取文件对应的魔数
*
* @param file 文件
* @return 魔数
*/
public static String getMagicNum(String file) {
try (InputStream stream = getStreamByFileName(file)) {
byte[] b = new byte[28];
stream.read(b, 0, 28);
return bytesToHex(b);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}