* Map<String ,Integer> map = new LinkedHashMap<>(); * map.put(“摩卡”,30); * map.put(“卡布奇诺”,27); * map.put(“拿铁”,27); * map.put(“香草拿铁”,30); * || * \ || / * \/ * 摩卡=30 * 卡布奇诺=27 * 拿铁=27 * 香草拿铁=30
将集合中的数据存入文件中
package MONA.demo01_作业题;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo01 {
public static void main(String[] args) throws Exception {
Map<String,Integer> 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();
System.out.println(map);
}
}
经过字符缓冲流的优化
package MONA.demo08_作业优化题;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo01 {
public static void main(String[] args) throws Exception {
Map<String,Integer> map = new LinkedHashMap<>();
map.put("摩卡",30);
map.put("卡布奇诺",27);
map.put("拿铁",27);
map.put("香草拿铁",30);
BufferedWriter bw = new BufferedWriter(new FileWriter("1.txt"));
for(String key : map.keySet()){
bw.write(key+"="+map.get(key));
bw.newLine();//换行
}
bw.close();
System.out.println("程序结束");
}
}
将保存到文件中的数据读取到集合中
package MONA.demo01_作业题;
import java.io.FileInputStream;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 将保存到文件中的数据读取到集合中
*/
public class Demo02 {
public static void main(String[] args) throws Exception {
Map<String ,Integer> map = new LinkedHashMap<>();
FileInputStream fis = new FileInputStream("1.txt");
byte[] bytes = new byte[1024];
int count = fis.read(bytes);
String str = new String(bytes,0,count);
String[] lines = str.split("\r\n");
for (String line : lines) {
String[] l = line.split("=");
//String --> int Integer
map.put(l[0],Integer.parseInt(l[1]));
}
System.out.println(map);
}
}
优化过后
package MONA.demo08_作业优化题;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo01 {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader("1.txt"));
String line = null;;
while ((line = br.readLine()) != null){
String[] l = line.split("=");
map.put(l[0],Integer.parseInt(l[1]));
System.out.println(line);
}
}
}