向文件a.txt中写入100道100以内的加减乘除题,并把答案写入b.txt

import java.util.*;

import java.io.*;

public class Main {

    private void flushList(File file) throws IOException {

        long startTime = System.currentTimeMillis();
        System.out.println("文件刷新开始:");
        Random random = new Random();
        BufferedWriter out = null;
        int times = 100;
        int a, b, c;

        try {
            out = new BufferedWriter(new FileWriter(file, false));
            for (int i = 1; i <= times; i++) {
                a = random.nextInt(100);
                b = random.nextInt(100);
                c = a + b;
                String string = String.format("题号%4d:%8d + %-4d == %-4d\n", i, a, b, c);
                out.write(string);
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
        System.out.println("文件刷新成功\n刷新时间:\t" + (System.currentTimeMillis() - startTime) + "ms\n");
    }

    private void printFunction(File file) throws IOException {

        System.out.println("文件内容打印列表如下:");
        BufferedReader in = null;

        try {
            in = new BufferedReader(new FileReader(file));
            String data;
            while ((data = in.readLine()) != null) {
                System.out.println(data);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }

    }

    private void runFunction() {

        long startTime = System.currentTimeMillis();
        File file = new File("d:\\java\\MathQuestions\\a.txt");
        System.out.println("题目文件目录:\n" + file.getAbsolutePath());
        System.out.println("是否刷新题目列表?YES -> 1 / NO -> 0:");
        Scanner reader = new Scanner(System.in);

        try {
            if (file.exists() == false) {
                if (file.getParentFile().exists() == false)
                    file.getParentFile().mkdirs();
                file.createNewFile();
            }
            if (reader.nextInt() == 1)
                flushList(file);
            printFunction(file);
        } catch (IOException error) {
            error.getMessage();
            throw new RuntimeException("\n程序运行出现问题,请尝试重新运行程序:");
        }

        System.out.println("程序运行完毕\n运行时间总计:\t" + (System.currentTimeMillis() - startTime) + "ms");

    }

    public static void main(String[] args) {
        new Main().runFunction();
    }
}

0

Leave a Reply

Your email address will not be published.