Java I/O 和collection 写了很长时间才写好的程序,做个纪念
2010-04-03 19:49
295 查看
import java.io.*; import java.util.*; public class Test6_Map { public static void main(String[] args) { MyMapStu mms = new MyMapStu(new File("exp.txt")); System.out.println("请输入要查找内容的学号!"); Scanner sc = new Scanner(System.in); long sno = sc.nextLong(); Student stu2 = new Student(sno, " "); if(mms.containsKey(stu2)) { System.out.println("The name is "+mms.get(stu2.getNo())); } else { System.out.println("No such person!"); } } } class Student { //简单定义学生类 private Long sno; private String sname; public Student() { } public Student(Long sno, String sname) { this.sno = sno; this.sname = sname; } public Long getNo() { return sno; } public String getName() { return sname; } } class MyMapStu { //定义此类主要是为了与文件连接,从中把数据读到map中。 Map<Long, String> map; public MyMapStu(File stuInfo) { if(!stuInfo.exists()) { try { stuInfo.createNewFile(); System.out.println("请建一个拥有30名学生学生信息表!"); BufferedWriter fos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(stuInfo))); byte[] bytes = new byte[40]; for(int i=0; i<30; i++) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = new String(); str = br.readLine(); fos.write(str, 0, str.length()); fos.newLine(); } fos.close(); } catch(IOException e) { e.printStackTrace(); } } try { map = new HashMap<Long, String>(); BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(stuInfo))); String stmp; while((stmp = fis.readLine())!=null) { System.out.println(stmp); String[] sArray = stmp.split(" "); Student stu = new Student(Long.parseLong(sArray[0]), sArray[1]); map.put(stu.getNo(), stu.getName()); } fis.close(); System.out.println(map); } catch(IOException e) { e.printStackTrace(); } } public boolean containsKey(Student stu) { if(map.containsKey(stu.getNo())) { return true; } else { return false; } } public String get(Long sno) { if(map.containsKey(sno)) { return map.get(sno); } else { return null; } } }
相关文章推荐
- 写好你程序之Java基础规约
- Java之路(1) --写好你程序之共通基础规约
- 使用gitbash将写好的普通java程序上传到github仓库中
- 如何写好Java程序呢
- (转)Java之路(3)--写好你程序之Java基础规约
- Java-集合框架Collection之Set(一)
- Java调用外部程序:Cannot allocate memory!
- JAVA 简单的抽奖程序
- Java中利用JMF编写摄像头拍照程序
- 08.JAVA小程序—模拟小球下落
- java----------C/S编程-----简单聊天程序
- 在运行java程序时出现 Error: could not open c:\program Files\Java\jre6\lib\amd64\jvm.cfg'
- 命令行运行java程序中的问题
- Java程序在Eclipse中可以运行,在命令行中却提示错误,找不到或无法加载主类!
- java程序的国际化2
- 算法竞赛入门经典java版程序ch4 UVa213
- java程序的递归算法,列出某个目录下的所有子目录和文件
- java 程序打开网页
- 使用Maven对JAVA程序打包-带主类、带依赖【转】
- Java Collection框架是什么?