public static void main(String[] args) throws Exception{
File file = new File("/Users/ww/Desktop/sww.txt");
FileOutputStream fos = new FileOutputStream(file, true);
String str = "swww";
fos.write(str.getBytes());
fos.flush();
fos.close();
FileInputStream finos = new FileInputStream(file);
StringBuffer sb = new StringBuffer();
byte[] bytes = new byte[1024];
int len = -1;
while ( (len = finos.read(bytes)) != -1) {
String str1 = new String(bytes,0,len,"UTF-8");
System.out.println(str1);
}
FileInputStream finos2 = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(finos2, "UTF-8");
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
finos.close();
}
EasyExcel导出到文件
private File getExcelFile(SelectVM vm, List<ExportCaseDTO> dataList) {
FileOutputStream fos = null;
try {
String encodedFileName = URLEncoder.encode("列表.xlsx", "UTF-8");
File file = File.createTempFile("CaseTemp_", encodedFileName);
fos = new FileOutputStream(file);
EasyExcel.write(fos, ExportCaseDTO.class).sheet().doWrite(dataList);
fos.flush();
return file;
} catch (IOException e) {
log.error("exportCase 失败,参数:{}", JSON.toJSONString(vm));
throw new Exception( "导出失败");
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
log.error("exportCase error", e);
}
}
}
public static void main(String[] args) {
List<MaterialType> list = new ArrayList<>();
MaterialType type = new MaterialType();
type.setSequence("s");
type.setMaterialName("测试s");
list.add(type);
MaterialType type1 = new MaterialType();
type1.setSequence("b");
type1.setMaterialName("测试b");
list.add(type1);
MaterialType type2 = new MaterialType();
type2.setSequence("c");
type2.setMaterialName("测试c");
list.add(type2);
MaterialType type3 = new MaterialType();
type3.setSequence("p");
type3.setMaterialName("测试p");
list.add(type3);
MaterialType type4 = new MaterialType();
type4.setSequence("s");
type4.setMaterialName("测试s-11");
list.add(type4);
Map<String, MaterialType> map = list.stream().collect(Collectors.toMap(MaterialType::getSequence, v -> v, (v1, v2) -> v1));
log.info(JSON.toJSONString(map));
Stream<String> stream = Stream.of("This", "is", "a", "test");
Map<String, Integer> map1 = stream.collect(Collectors.toMap(Function.identity(), String::length));
log.info(JSON.toJSONString(map1));
}
下面参考:Stream流Collectors.toMap用法_stream().collect(collectors.tomap-CSDN博客
使用toMap()函数之后,返回的就是一个Map了,自然会需要key和value。
toMap()的第一个参数就是用来生成key值的,第二个参数就是用来生成value值的。
第三个参数用在key值冲突的情况下:如果新元素产生的key在Map中已经出现过了,第三个参数就会定义解决的办法。
在.collect(Collectors.toMap(Person::getId, v -> v, (a,b)->a))中:
第一个参数:Person:getId表示选择Person的getId作为map的key值;
第二个参数:v->v表示选择将原来的对象作为Map的value值
第三个参数:(a,b)->a中,如果a与b的key值相同,选择a作为那个key所对应的value值。
如果key冲突,不加(a,b)->a会报如下错误:
重复的key