PrintWriter out = new PrintWriter(new FileWriter(" students.txt",true)); 做 { //从用户那里获取信息以写入文件 System.out.print("输入学生ID:"); idNo = keyIn.nextLine(); System.out.print("输入学生姓名:"); name = keyIn.nextLine(); System.out.print("输入学生成绩:"); grades = keyIn.nextInt(); keyIn.nextLine(); //清除缓冲区
out.println(idNo +" " +name +" " +grades); //write line to output file
System.out.print("Do You Have Another Student To Process: ");
response = keyIn.next().charAt(0);
keyIn.nextLine(); //clear buffer
}while(response != 'n');
//close files
out.close();
//in.close();
中断;
案例2://将学生测试标记写入results.txt
答案 0 :(得分:0)
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer >();
while ((line = br.readLine()) != null) {
String temp[]=line.split(" ");
if (map.containsKey(Integer.parseInt(temp[0]))) {
int val=hmap.get[Integer.parseInt(temp[0])];
val+=Integer.parseInt(temp[2]);
map.put(Integer.parseInt(temp[0]),val);
} else {
map.put(Integer.parseInt(temp[0]),Integer.parseInt(temp[2]));
}
}
}
try{
PrintWriter writer = new PrintWriter("results.txt", "UTF-8");
Iterator it = hmap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
writer.println(pair.getKey() + " " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
writer.close();
} catch (IOException e) {
// do something
}