java基础——IO以及文件的练习

第一题:.将day19-笔记.txt中每一行前面加上行号和冒号
public class Exercise1 {
        public static void main(String[] args) throws IOException {
                List<String> list = new ArrayList<String>();  // 定义List<String>, 用来存储行数据
                // 定义LineNumberReader, 用来读取行数据
                LineNumberReader lnr = new LineNumberReader(new FileReader("day19-笔记.txt"));
                String line;                 
                while ((line = lnr.readLine()) != null)      // 定义循环读取数据, 加上行号和冒号, 存入List
                        list.add(lnr.getLineNumber() + ": " + line);
                lnr.close();

                BufferedWriter bw = new BufferedWriter(new FileWriter("day19-笔记.txt"));  // 定义BufferedWriter
                for (String s : list) {               // 迭代List, 将存储的行写出
                        bw.write(s);
                        bw.newLine();
                } 
                bw.close();
        }
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
 第二题:将day19-笔记.txt中的所有行反转(第一行换到最后一行, 第二行换到倒数第二行)
public class Exercise2 {
        public static void main(String[] args) throws IOException {
                BufferedReader br = new BufferedReader(new FileReader("day19-笔记.txt")); // 定义BufferedReader, 用来读取行数据
                List<String> list = new ArrayList<String>();        // 定义List<String>, 用来存储行数据
                String line;
                while ((line = br.readLine()) != null)          // 定义循环, 读取数据到List中
                        list.add(line);
                br.close();
  
                BufferedWriter bw = new BufferedWriter(new FileWriter("day19-笔记.txt")); // 定义BufferedWriter
                for (int i = list.size() - 1; i >= 0; i--) {        // 倒着遍历List, 将数据写出
                        bw.write(list.get(i));
                        bw.newLine();
                }
                bw.close();
        }
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
第三题:将day19-笔记.txt中的所有字符按照码表值排序, 存入另一个文件中
public class Exercise3 {
        public static void main(String[] args) throws IOException {
                BufferedReader br = new BufferedReader(new FileReader("day19-笔记.txt")); // 定义BufferedReader
                TreeSet<Character> ts = new TreeSet<Character>(new CharComparator());  // 定义TreeSet<Character>
                int ch;                  // 读取文件数据, 存入TreeSet排序
                while ((ch = br.read()) != -1) {
                        if (ch == '\r' || ch == '\n' || ch == ' ' || ch == '\t')
                        continue;
                        ts.add((char)ch);
                }
                br.close();
  
                BufferedWriter bw = new BufferedWriter(new FileWriter("sort.txt"));   // 定义BufferedWriter
                for (char c : ts)               // 迭代TreeSet, 将数据写出到另一个文件
                bw.write(c);
                bw.close();
        }
}
class CharComparator implements Comparator<Character> {
        public int compare(Character o1, Character o2) {
                return o1 - o2 != 0 ? o1 - o2 : 1;
        }
}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------
第四题:编写一个程序, 该程序只能运行10次, 每次运行时提示剩余次数, 10次之后提示已到期
public class Exercise4 {
        public static void main(String[] args) throws IOException {
                BufferedReader br = new BufferedReader(new FileReader("times.txt")); // 定义输入流, 指向times.txt
                int times = Integer.parseInt(br.readLine());       // 读取一行数据, 转为int值
                br.close();                // 关闭输入流
  
                if (times > 0) {              // 如果次数大于0
                        System.out.println("欢迎使用Xxx软件, 剩余使用次数: " + times);  // 打印次数
                        FileWriter fw = new FileWriter("times.txt");      // 定义输出流, 指向times.txt
                        fw.write(--times + "");            // 将次数减1, 写回文件中. 注意: 将次数写回文件的时候要转为String
                        fw.close();               // 关闭输出流
                } else {                // 如果次数不大于0
                        System.out.println("软件已到期");         // 提示已到期
                }
        }
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
第五题:从键盘接收3个学生的考试成绩, 对其按照总分排序, 输出到屏幕. 
考试成绩输入格式:
张三,80,85,80
李四,70,70,80
王五,90,90,90
屏幕输出格式:
王五,90,90,90,270 
张三,80,85,80,245
李四,70,70,80,220


public class Exercise5 {
        public static void main(String[] args) throws IOException, InterruptedException {
                System.out.println("请输入学生成绩:");
  
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 定义BufferedReader
                TreeSet<Student> set = new TreeSet<Student>();        // 为了要排序, 所以创建TreeSet集合
  
                for (;;) {            
                        String line = br.readLine();
                        if ("quit".equals(line)) {
                                br = new BufferedReader(new FileReader("stu.txt"));
                                continue;
                        } else if (line == null) {
                                br.close();
                                break;
                        }

                String[] arr = line.split(",");        // 读取数据, 按逗号分割
                Student stu = new Student(arr[0], Integer.parseInt(arr[1]), Integer.parseInt(arr[2]), Integer.parseInt(arr[3]));    
                set.add(stu);    // 每次将读取到的数据封装成一个对象, 装到集合中排序
                }
  
                PrintStream ps = new PrintStream(new FileOutputStream("stu.txt"));
                System.setOut(ps);
                for (Student stu : set)   
                        System.out.println(stu); // 迭代TreeSet集合, 打印结果
                ps.close();
        }
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
第六题:从键盘输入接收一个文件夹路径, 将该文件夹下的所有.java文件的文件名写入到java.txt文件中
public class Exercise1 {
        public static void main(String[] args) throws IOException {
                System.out.println("请输入一个文件夹路径:");
                File dir = Util.getDir();
                String[] arr = dir.list();   // 获取子文件名
                BufferedWriter bw = new BufferedWriter(new FileWriter("java.txt"));
                for (String name : arr)
                        if (name.endsWith(".java")) { // 判断如果是.java结尾就写出
                                bw.write(name);
                                bw.newLine(); 
                        }
                        bw.close();
          }
}
//这里定义了Util类,以后的代码为了简单可以省略该类,是在控制台中输入对应的路径或者文件。
public class Util {
        public static File getDir() throws IOException {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                while (true) {
                        File file = new File(br.readLine()); // 从键盘读取一个路径, 封装成File对象
                        if (!file.exists())      // 如果不存在, 提示, 重输
                                System.out.println("您输入的路径不存在, 请重新输入:");
                        else if (!file.isDirectory())   // 如果不是文件夹, 提示, 重输
                                System.out.println("您输入的不是文件夹路径, 请重新输入:");
                        else
                        return file;   
                }
        } 
        public static File getFile() throws IOException {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                while (true) {
                        File file = new File(br.readLine()); 
                        if (!file.exists())      
                                System.out.println("您输入的路径不存在, 请重新输入:");
                        else if (!file.isFile())   
                                System.out.println("您输入的不是文件路径, 请重新输入:");
                        else
                        return file;   
                }
        } 
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
第七题:从键盘输入接收一个文件夹路径, 将该文件夹下的所有子文件名写入到name.txt中, 包括子文件夹下的子文件
public class Exercise2 {
        public static void main(String[] args) throws IOException {
                System.out.println("请输入一个文件夹路径: ");
                File dir = Util.getDir();      // 调用工具类中的方法, 从键盘接收一个文件路径封装成File对象
                System.setOut(new PrintStream("name.txt"));  // 改变默认输出流, 指向文件
                Exercise2.writeSubfileNames(dir, 0);   // 将dir文件夹下所有子文件名(包括子文件夹的子文件)写出
        }        
        private static void writeSubfileNames(File dir) {
                File[] subFiles = dir.listFiles();    // 获取当前文件夹下所有的子文件组成的File[]
                if (subFiles != null)       // 有些系统文件夹不允许获取子文件, 会返回null, 为了避免空指针异常所以判断
                        for (File subFile : subFiles) {    // 循环遍历所有子文件
                                System.out.println(subFile.getName()); // 打印每一个子文件的名字
                                if (subFile.isDirectory())    // 如果是一个文件夹
                                        writeSubfileNames(subFile);   // 再打印出这个子文件夹下所有子文件的名字
                        }
        }

        private static void writeSubfileNames(File dir, int lv) { // lv记住递归的次数
                File[] subFiles = dir.listFiles();    
                if (subFiles != null)       
                        for (File subFile : subFiles) {    
                                for (int i = 0; i < lv; i++)
                                        System.out.print("\t");
                                System.out.println(subFile.getName()); 
                                if (subFile.isDirectory())    
                                        writeSubfileNames(subFile, lv + 1);   // 每递归一次加1
                        }
        }
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
第八题:从键盘输入接收一个文件夹路径, 统计该文件夹大小.
public class Exercise3 {
        public static void main(String[] args) throws IOException {
                System.out.println("请输入一个文件夹路径: ");
                File dir = Util.getDir();
                System.out.println(getLength(dir));
        }
        public static long getLength(File dir) {
                long len = 0;       // 定义变量用来记住大小
                File[] subFiles = dir.listFiles();  // 找到所有子文件
                if (subFiles != null)     // 为了避免系统文件不允许访问
                        for (File subFile : subFiles)  // 遍历每一个子文件
                                if (subFile.isFile())
                                        len += subFile.length();
                                else 
                                        len += getLength(subFile);
                                // len += subFile.isFile() ? subFile.length() : getLength(subFile); // 如果是文件则加上文件大小, 是文件夹则递归计算文件夹大小
        
return len;
        }
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
第九题:从键盘输入接收一个文件夹路径, 删除该文件夹.
public class Exercise4 {
                public static void main(String[] args) throws IOException {
                        System.out.println("请输入一个文件夹路径: ");
                        File dir = Util.getDir();
                        System.out.println("确定要删除\"" + dir.getAbsolutePath() + "\"吗? (Y/N)");
                        if ("Y".equalsIgnoreCase(new BufferedReader(new InputStreamReader(System.in)).readLine()))
                                deleteDir(dir);

                        System.out.println(dir.exists() ? "出错了" : "删除成功!");
                }

                public static void deleteDir(File dir){
                        File[] subFiles = dir.listFiles();           // 获取所有子文件
                        if (subFiles != null)                              // 避免NullPointerException
                                for (File subFile : subFiles)           // 遍历
                                        if (subFile.isFile())            // 如果是文件就删除
                                                subFile.delete(); 
                                        else                                    // 如果是文件夹就递归, 删除文件夹
                                                deleteDir(subFile);
                        dir.delete();                                        // 删除所有子文件之后, 删除当前文件夹
                }
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
第十题:从键盘输入接收两个文件夹路径, 将一个文件夹拷贝到另一个文件夹中.
public class Exercise5 {
        public static void main(String[] args) throws IOException {
                System.out.println("请输入源文件夹路径:");
                File src = Util.getDir();
                System.out.println("请输入目标文件夹路径:");
                File dest = Util.getDir();
                copyDir(src, dest);
        }
        /*
        * src:  F:\Itcast\20120413\Code\day20-8
        * dest: F:\
        * newDir: F:\day20-8
        */

        public static void copyDir(File src, File dest) throws IOException {
                File newDir = new File(dest, src.getName()); // 在dest文件夹下创建和src同名的文件夹
                newDir.mkdir();
  
                File[] subFiles = src.listFiles();    // 获取src下所有子文件
                if (subFiles != null) {
                        for (File subFile : subFiles) {    // 循环遍历
                                if (subFile.isFile()) {     // 如果是文件直接考到新建的文件夹下
                                        FileInputStream fis = new FileInputStream(subFile);
                                        FileOutputStream fos = new FileOutputStream(new File(newDir, subFile.getName()));
                                        byte[] buffer = new byte[1024];
                                        int len;
                                        while ((len = fis.read(buffer)) != -1)
                                                fos.write(buffer, 0, len);
                                                fis.close();
                                                fos.close();
                                } else {        // 如果是文件夹, 递归拷贝子文件夹
                                        copyDir(subFile, newDir);
                                }
                        }
                }
        }
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------
第十一题:分割文件
public class Exercise6 {
        public static void main(String[] args) throws IOException {
                System.out.println("请输入要分割的文件路径:");
                File file = Util.getFile();       // 获取文件路径
  
                File tempDir = new File(file.getParent(), ".temp"); // 创建文件夹
                tempDir.mkdir();
  
                long partLen = file.length() / 3 + 1;    // 每一段的大小
                FileInputStream fis = new FileInputStream(file); // 定义流从文件中读数据
                for (int i = 0; i < 3; i++) {      // 循环3次
                        FileOutputStream fos = new FileOutputStream(new File(tempDir, i + ""));  // 每次定义一个输出流
                        byte[] buffer = new byte[(int) partLen];  // 定义字节数组, 长度为一份大小
                        int len = fis.read(buffer);      // 将数据读入数组
                        fos.write(buffer, 0, len);      // 写出到小文件中
                        fos.close();         // 关闭输出流
                }
                fis.close();
                file.delete();    // 删除原文件
                tempDir.renameTo(file);  // 改文件夹名字
        }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值