Java中一些常用的方法

來源:互聯網
上載者:User

標籤:generated   ted   技術   run   out   filename   代碼   imp   靜態方法   

1.計算程式運行時常

long start = System.currentTimeMillis();………long end = System.currentTimeMillis();System.out.println("程式運行時常 : "+(end-start)+" ms");
2.檔案讀寫
    String fileName = "/home/test";//定義寫檔案路徑    FileWriter writer = null;//檔案讀寫流    public void write_To_File(){        writer = new FileWriter(fileName, true);        try {                   writer.write("Hello World!");              } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }     }
3.立flag

  設定布爾變數,用來在程式運行時對一些邏輯進行標記。其中false和true需要自己定義其含義。因此在設定flag的時,需要注意false以及true對應的含義。否則這些邏輯上的錯誤很難被檢查出來。

    boolean flag = true;    …    …    If()    }    …    /* 根據程式運行邏輯進行對flag的修改 */    else{      }    
4.使用HashMap

  聲明myMap為HashMAp類型

HashMap<String,String> myMap=new HashMap<String,String>();

  其中HashMap中的第一個參數,第二個參數為String

  可以使用HashMap來構造key,value一一對應的結構。

  例如:學號對應一個姓名

            

  

 

 

 

    則可以使用put來構造HashMap

myMap.put("1","張三");myMap.put("2","李四");myMap.put("3","王五");myMap.put("4","趙六");

  可以使用get來查看key對應的value

myMap.get("1");//會返回張三
5.將excel的去重後內容放到list中
    String path = "/home/allNumber.csv";    public static ArrayList<String> myList = new ArrayList<String>();//聲明list, 內容為String類型    public static void createList(String path) throws IOException{    BufferedReader reader = new BufferedReader(new FileReader(new File(path)));            String line = "";            while((line=reader.readLine())!=null){//賦值並進行判斷                if(!myListlist.contains(line )){//去重                    myList.add(line );                }            }            reader.close();    }

  首先聲明檔案讀寫流,傳入參數path為檔案路徑;

  while迴圈體中需要判斷是否已經到了檔案的末尾,同時進行賦值操作;

  由於需要進行去重操作,只需要每次向myList中添加資料之前前進行判斷該資料是否已經存在;

  記住最後要將檔案的讀寫流關閉 reader.close();

6.定時進行寫檔案

  使用靜態方法

    public class test {            public static void executeFixedRate() throws IOException {            ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);           /*            * 參數1 new count() 表示啟動並執行方法            * 參數2 0 表示第一次調用等待 0ms 之後運行count中的run方法            * 參數3 5000 表示之後每經過5000ms再次調用            * 參數4 TimeUnit.MILLISECONDS 設定時間為毫秒            */            executor.scheduleAtFixedRate(new count(),0,5000,TimeUnit.MILLISECONDS);        }        static class count implements Runnable{                        private String fileName = "/home/test";            private FileWriter writer = null;            //設定日期格式            private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            public void run(){//運行代碼                   try {                    writer = new FileWriter(fileName, true);                    writer.write("Hello World"+df.format(new Date())+"\n");                    writer.flush();                                    } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }           }            public static void main(String[] args) throws Exception {            test.executeFixedRate();        } }
7.第二種定時寫檔案

  使用Timer類

    public class test {                private static void executeFixedRate() {            Timer timmerTask = new Timer();            Calendar calEnviron = Calendar.getInstance();            // 每00:00:00 開始執行            calEnviron.set(Calendar.HOUR_OF_DAY, 0);            calEnviron.set(Calendar.MINUTE, 0);            calEnviron.set(Calendar.SECOND, 0);                        // date制定間            Date dateSetter = new Date();            dateSetter = calEnviron.getTime();            // nowDate前間            Date nowDateSetter = new Date();            // 所間差距現待觸發間間隔            long intervalEnviron = dateSetter.getTime() - nowDateSetter.getTime();            if (intervalEnviron < 0) {                calEnviron.add(Calendar.DAY_OF_MONTH, 1);                dateSetter = calEnviron.getTime();                intervalEnviron = dateSetter.getTime() - nowDateSetter.getTime();            }            //第一次運行直接運行test的run            if(flag_first){                timmerTask.schedule(new count(), 0, 1 * 1000 * 60 * 60 * 24);            }//以後都經過觸發間隔之後運行            else{                timmerTask.schedule(new count(), intervalEnviron, 1 * 1000 * 60 * 60 * 24);            }        }        static class count implements Runnable{                        private String fileName = "/home/test";            private FileWriter writer = null;            //設定日期格式            private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            public void run(){//運行代碼                   try {                    writer = new FileWriter(fileName, true);                    writer.write("Hello World"+df.format(new Date())+"\n");                    writer.flush();                                    } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }           }        public static void main(String[] args) throws Exception {            test.executeFixedRate();        }    }

 

Java中一些常用的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.