fos.write(key.getBytes());请问这句代码中的.getBytes()是什么意思?以及 fos.write(map.get(key).toString().getBytes());这句代码中为什么还要.toString().getBytes()转这么多形式,并且解释一下转toString和转getBytes是什么意思,谢谢。
package com.nt.sz.Day17.Demo01_练习题;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) throws Exception {
// 1. 将集合中的数据存入文件中
//Map map = new LinkedHashMap<>();
// map.put("摩卡", 30);
// map.put("卡布奇诺", 27);
// map.put("拿铁", 27);
// map.put("香草拿铁", 30);
Map map = new LinkedHashMap<>();
map.put("摩卡", 30);
map.put("卡布奇诺", 27);
map.put("拿铁", 27);
map.put("香草拿铁", 30);
FileOutputStream fos = new FileOutputStream("1.txt");
for (String key : map.keySet()) {
fos.write(key.getBytes());
fos.write("=".getBytes());
fos.write(map.get(key).toString().getBytes());
fos.write("\r\n".getBytes());
}
fos.close();
}
}
https://www.cnblogs.com/gavin5033/p/12594495.html
主要解决编码问题
.getBytes()
是String对象封装的方法,作用是将字符串转换成字节数组
。fos.write(map.get(key).toString().getBytes())
中使用get(key).toString()
是因为,get(key)
得到的是Integer类型,Integer这个类没有封装getBytes()方法,所以需要使用Integer的toString()
方法转换成String对象,然后才能使用getBytes()方法。
首先,toString是转为String对象,getBytes是String里面的方法,其次,你这个是字节流,这个write方法需要byte数组
FileOutputStream.write必须写入字节格式 getBytes()就是获取字节