IO习题

 1.Java实现将九九乘法表输入到文本文件

public class Test1 {

         public static void main(String[] args) throws FileNotFoundException {

                   System.setOut(new PrintStream("table99.txt"));//重定项屏幕输出到ps对象中

                   for (int i = 1; i < 10; i++) {

                            for (int j = 1; j <= i; j++) {

                                     System.out.print(j + " * " + i + " = " + i * j +"\t");

                            }

                            System.out.println();

                   }

         }

}

2.从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,

         并按重复次数排序,如果次数相同按姓名字母排序:

1,zhangsan,28

2,lisi,35

3,zhangsan,28

4,wangwu,35

5,zhangsan,28

6,lisi,35

7,zhaoliu,28

8,tianqi,35

class NameBean implements Comparable<NameBean> {

         // 名字

         private String name;

         // 出现次数

         private Integer count;

         public NameBean(String name, Integer count) {

                   super();

                   this.name = name;

                   this.count = count;

         }

         public String toString() {

                   return name + " 出现 " + count;

         }

 

         public int compareTo(NameBean bean) {

                   if (this.count > bean.count) {

                            return 1;

                   } else if (this.count < bean.count) {

                            return -1;

                   } else {

                            return this.name.compareTo(bean.name);

                   }

         }

}

 

public class Test2 {

         public static void readFile(File file) throws IOException {

                   Scanner sc = new Scanner(file);

                   Map<String, Integer> nameMap = new TreeMap<String, Integer>();

 

                   // 名字和重复次数的集合

                   Set<NameBean> nameSet = new TreeSet<NameBean>();

                   while (sc.hasNextLine()) {

                            String line = sc.nextLine();

                            String[] info = line.split(",");

                            String name = info[1];

                            if (nameMap.containsKey(name)) {

                                     int count = nameMap.get(name);

                                     nameMap.put(name, count + 1);

                            } else {

                                     nameMap.put(name, 1);

                            }

                   }

                   Set<Map.Entry<String, Integer>> entrys = nameMap.entrySet();

 

                   Iterator<Map.Entry<String, Integer>> it = entrys.iterator();

                   while (it.hasNext()) {

                            Map.Entry<String, Integer> entry = it.next();

                            nameSet.add(new NameBean(entry.getKey(), entry.getValue() - 1));

                   }

                   System.out.println(nameSet);

         }

 

         public static void main(String[] args) throws IOException {

                   readFile(new File("student.txt"));

         }

}

 

 

3.编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,

         并将原来文件的扩展名从.java改为.jad。

public class Test3 {

         public static void copy(File src, File dest) throws IOException {

                   if (src == null || !src.exists()) {

                            System.out.println("源不存在");

                            return;

                   }

                   if (dest != null && !dest.exists()) {

                            dest.mkdir();

                   }

                   File[] fs = src.listFiles(new FilenameFilter() {

                            public boolean accept(File dir, String name) {

                                     return name.endsWith(".java");

                            }

                   });

                   OutputStream out = null;

                   InputStream in = null;

                   for (File f : fs) {

                            String oldName = f.getName();

                            StringBuilder newName = new StringBuilder();

                            newName.append(oldName.substring(0, oldName.lastIndexOf('.'))).append(".jad");

                            in = new FileInputStream(f);

                            out = new FileOutputStream(dest.getPath() + File.separator

                                               + newName.toString());

 

                            byte[] buff = new byte[1024];

                            int len = 0;

                            while ((len = in.read(buff)) != -1) {

                                     out.write(buff, 0, len);

                            }

                            out.close();

                            in.close();

                   }

         }

 

         public static void main(String[] args) throws IOException {

 

                   File src = new File("d:/java");

                   File dest = new File("d:/jad");

                   copy(src, dest);

         }

}

 

4.从键盘读入一行字符串,这行字符串内容类似如下:"2,10,1,22,19,30";

         输入升序排序或者降序排序,然后根据输入打印排序结果

public class Test4 {

         public static void main(String[] args) {

                  

                   Scanner sc = new Scanner(System.in);

                   sc.useDelimiter("\n");

                   Set<Integer> set = new TreeSet<Integer>(new Comparator<Integer>() {

                            public int compare(Integer o1, Integer o2) {

                                     return o1.compareTo(o2) * -1;

                            }

                   });

                   while(sc.hasNextLine()){

                            set.clear();

                            String ele  = sc.nextLine();

                            String[] arr = ele.split(",");

                            for (String s : arr) {

                                     set.add(new Integer(s));

                            }

                            System.out.println("排序后= "+set);

                   }

                  

         }

}

5.删除一个目录(注意:要删除目录必须删除目录下的文件和子目录)

public class Test5 {

 

         public static void delDir(File dir) {

                   if (dir == null || !dir.exists()) {

                            return;

                   }

                   if (dir.isFile()) {

                            dir.delete();

                   } else {

                            File[] fs = dir.listFiles();

                            for (File f : fs) {

                                     delDir(f);

                                     if (dir.list().length == 0) {// 空目录

                                               dir.delete();

                                     }

                            }

                   }

         }

 

         public static void main(String[] args) {

                   File dir = new File("D:/jad");

                   delDir(dir);

         }

}

 

6.将一个文件中的内容倒序(不允许用第二个文件)

public class Test6 {

 

         public static void reverse(String file) {

 

                   int total = 0;// 读取的总字节数

                   char[] buff = new char[30];

                   try (Reader in = new FileReader(file);) {

 

                            int len = 0;

                            while ((len = in.read(buff)) != -1) {

                                     total += len;

                            }

                   } catch (Exception e) {

                   }

                   //==============

                   try (Writer out = new FileWriter(file);) {

                            for (int i = total - 1; i >= 0; i--) {

                                     out.write(buff[i]);

                            }

                   } catch (Exception e) {

 

                   }

 

         }

 

         public static void main(String[] args) {

                   // start哥曾信佛但佛信曾哥end

                   reverse("out.txt");

         }

}

 

7.public class GuessDemo {

         /**

          * 1.系统先一个生成[1,100]之间的随机数; 2.程序得到键盘录入的数据,要做检查

          */

         public static void guess() {

                   Integer ran = new Random().nextInt(100) + 1;// [1,100]

 

                   System.out.println("随机数= " + ran);

                   Scanner sc = new Scanner(System.in);

                   while (sc.hasNextLine()) {

                            String input = sc.nextLine();

                            // 检查input是否由数字组成

                            if (!input.matches("\\d+")) {

                                     System.out.println("亲,请输入数字");

                            } else {

                                     Integer num = new Integer(input);

                                     if (num > 100 || num < 1) {

                                               System.out.println("亲,请输入的[1,100]之间的数字");

                                     } else {

                                               // [1,100];

 

                                               switch (num.compareTo(ran)) {

                                               case 1:

                                                        // 此时num> ran

                                                        System.out.println("亲,你输入大了");

                                                        break;

                                               case -1:

                                                        System.out.println("亲,你输入小了");

                                                        break;

                                               default:

                                                        System.out.println("亲,恭喜你中奖了");

                                                        return;

                                               }

                                     }

                            }

                   }

         }

 

         public static void main(String[] args) {

                   guess();

         }

}

posted @ 2016-02-15 18:09  starskyhu  阅读(403)  评论(0编辑  收藏  举报