FileUtils

来源:互联网 发布:ember.js 教程 编辑:程序博客网 时间:2024/05/22 04:53
public class FileUtils {
// 根据路径获取文件里面的内容转为List
public static List<String> getCustList(String path) throws Exception {
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
// 使用转换流将字节流转为字符流
InputStreamReader reader = new InputStreamReader(inputStream);
// 字节流转为字符流
BufferedReader bufferedReader = new BufferedReader(reader);
String line = "";
StringBuilder builder = new StringBuilder();
List<String> custList = new ArrayList<>();
if (null != (line = bufferedReader.readLine())) {
builder.append(line);
}
// 调用fastjson方法返回list
custList = JSON.parseArray(builder.toString(), String.class);
// 关流
reader.close();
return custList;
}


// 根据输入流获取list集合
public static List<String> getCustListFromFile(InputStream inputStream) throws Exception {
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = "";
List<String> custList = new ArrayList<>();
StringBuilder builder = new StringBuilder();
if (null != (line = bufferedReader.readLine())) {
builder.append(line);
}
// 调用fastJson方法将stringbuilder里面内容转为List集合
custList = JSON.parseArray(builder.toString(), String.class);
// 关流
reader.close();
return custList;
}


// 传入的文件不为空
public static boolean isNotNull(MultipartFile file) {


return file != null && !file.isEmpty() && file.getSize() > 0;
}


// byte字节转为kb和mb
public static String bytes2kb(long bytes) {
// 将long型字节转为java
BigDecimal filesize = new BigDecimal(bytes);
BigDecimal megabyte = new BigDecimal(1024 * 1024);
BigDecimal divide = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP);
float returnValue = divide.floatValue();
if (returnValue > 1) {
return returnValue + "MB";
}
BigDecimal kiloBytes = new BigDecimal(1024);
returnValue = filesize.divide(kiloBytes, 2, BigDecimal.ROUND_UP).floatValue();
return returnValue + "KB";
}


// 解决跨越问题
public static void crossDomain(HttpServletResponse response) {


response.setHeader("Access-Controller-Allow-Origin", "*");
response.setHeader("Access-Controller-Allow-Methods", "POST,GET");
}
public static void main(String[] args) throws Exception {
String bytes = FileUtils.bytes2kb(1024*1024*2);
System.out.println(bytes);
String path="a.txt";
InputStream inputStream=new FileInputStream(new File(path));
List<String> list = FileUtils.getCustListFromFile(inputStream);
System.out.println(list);

}
}