java 常用模块代码

1.文件的读写操作

(1)进行读操作

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileTest {
    public static void main(String[] args) {
        try {
            BufferedReader br=new BufferedReader(new FileReader("doc/user.txt"));
            String str;
            while ((str=br.readLine())!=null){
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

(2)进行写操作

import java.io.*;

public class FileUtils {
    public static void main(String[] args) {
        inputStreamReader();
    }

    public static void inputStreamReader() {
        //1.创建输入流对象,将流理解为一只笔,输入流为读取数据,输出流为写数据
        InputStream inputStream = null;
        FileOutputStream fos=null;

        try {
            //2.实例化输入流对象
            inputStream = new FileInputStream("E:\javaProject\javaSEProject\UtilSummary\res\novel.txt");
            //3.将读取的内容写入指定的文件夹的文件中

            //4.定义输出流的目标文件
            File file=new File("E:\javaProject\javaSEProject\UtilSummary\res\novel_copy1.txt");
            //5.实例化输出流对象
            fos = new FileOutputStream(file);
            //6.指定每次读取文件的大小
            byte[] bs = new byte[1024];
            int temp=-1;
            while ((temp=inputStream.read(bs))!=-1){
                //7,向指定目标文件写数据
                fos.write(bs,0,temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //8.inputStream、fos不为空,则关闭文件流
                if (inputStream != null&&fos!=null) {
                    inputStream.close();
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.Timer定时操作+时间格式化输出显示

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTool {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        Timer timer=new Timer();
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
                System.out.println("hellolucky");
            }
        };
        timer.schedule(timerTask,10000);

    }
}

后台输出为:

原文地址:https://www.cnblogs.com/luckyplj/p/10585338.html