【Java】【基礎篇】day18:IO流(字符流讀寫)

前言

本期任務:畢向東老師Java視頻教程學習筆記(共計25天)



代碼

/*
字符流和字節流:

字節流兩個基類:
InputStream   OutputStream


字符流兩個基類:
Reader Writer

先學習一下字符流的特點。

既然IO流是用於操作數據的,
那麼數據的最常見體現形式是:文件。

那麼先以操作文件爲主來演示。

需求:在硬盤上,創建一個文件並寫入一些文字數據。

找到一個專門用於操作文件的Writer子類對象。FileWriter。  後綴名是父類名。 前綴名是該流對象的功能。


*/
import java.io.*;
public class FileWriterDemo {
    public static void main(String[] args) throws Exception{
        //創建一個FileWriter對象。該對象一被初始化就必須要明確被操作的文件。
        //而且該文件會被創建到指定目錄下。如果該目錄下已有同名文件,將被覆蓋。
        //其實該步就是在明確數據要存放的目的地。
        FileWriter fw = new FileWriter("demo.txt");

        // 調用write方法,將字符串寫入到流中
        fw.write("fsgd");

        //刷新流對象中的緩衝中的數據。
        //將數據刷到目的地中。
//        fw.flush();

        //關閉流資源,但是關閉之前會刷新一次內部的緩衝中的數據。
        //將數據刷到目的地中。
        //和flush區別:flush刷新後,流可以繼續使用,close刷新後,會將流關閉。
        fw.close();


    }
}
/*
IO異常的處理方式。
*/

import java.io.*;

public class FileWriterDemo2 {
    public static void main(String[] args) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("demo.txt");
            fw.write("dfalkjf;");
        } catch (IOException e) {
            System.out.println("catch: " + e.toString());
        } finally {
            try {
                if (fw != null)
                    fw.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }

        }
    }
}
/*
演示對已有文件的數據續寫。
*/

import java.io.*;

public class FileWriterDemo3 {
    public static void main(String[] args) throws IOException {
        //傳遞一個true參數,代表不覆蓋已有的文件。並在已有文件的末尾處進行數據續寫。
        FileWriter fw = new FileWriter("demo.txt", true);
        fw.write("\r\n這是續寫的部分內容。。。。\r\n");
        fw.close();
    }
}
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args)throws IOException {
        //創建一個文件讀取流對象,和指定名稱的文件相關聯。
        //要保證該文件是已經存在的,如果不存在,會發生異常FileNotFoundException

        FileReader fr = new FileReader("demo.txt");

        //調用讀取流對象的read方法。
        //read():一次讀一個字符。而且會自動往下讀。若讀取完畢,則返回-1

        int ch = 0;
        while ((ch=fr.read())!=-1){
            System.out.println((char)ch);
        }

        fr.close();
    }
}
import java.io.FileReader;
import java.io.IOException;

/*
第二種方式:通過字符數組進行讀取。
*/
public class FileReaderDemo2 {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("demo.txt");

        //定義一個字符數組。用於存儲讀到字符。
        //該read(char[])返回的是讀到字符個數,文檔讀取完畢,則個數爲-1。

        char[] buf = new char[1024];

        int num = 0;
        while ((num = fr.read(buf)) != -1) {
            System.out.println(new String(buf, 0, num));
        }

        fr.close();

    }
}
//將C盤一個文本文件複製到D盤。

/*
複製的原理:
其實就是將C盤下的文件數據存儲到D盤的一個文件中。

步驟:
1,在D盤創建一個文件。用於存儲C盤文件中的數據。
2,定義讀取流和C盤文件關聯。
3,通過不斷的讀寫完成數據存儲。
4,關閉資源。
*/

import java.io.*;
public class CopyText {
    public static void main(String[] args) throws Exception{
        FileReader fr = new FileReader("demo.txt");
        FileWriter fw = new FileWriter("demo_copy.txt");

        char[] buf = new char[1024];
        int num = 0;

        while ((num=fr.read(buf))!=-1){
            fw.write(buf, 0, num);
        }

        fr.close();
        fw.close();
    }
}

import java.util.*;
import java.text.*;

public class DateDemo {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d);

        // 將模式封裝到SimpleDateFormat對象中,然後調用format方法讓模式格式化指定Date對象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E kk:mm:ss");
        System.out.println("time: "+sdf.format(d));

        long l = System.currentTimeMillis();
        System.out.println(new Date(l));
    }
}
import java.util.*;
import java.text.*;

public class CalendarDemo {
    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        System.out.println(c);

        String[] mons = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"};
        String[] weeks = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int week = c.get(Calendar.DAY_OF_WEEK);

        System.out.println(year + "年" + mons[month] + day + "日" + weeks[week]);

    }
}
import java.util.*;

/*
兩個練習:
1,獲取任意年的二月有多少天。
	思路:根據指定年設置一個時間就是
	c.set(year,2,1)//某一年的3月1日。
	c.add(Calenar.DAY_OF_MONTH,-1);//3月1日,往前推一天,就是2月最後一天。



2,獲取昨天的現在這個時刻。
	c.add(Calenar.DAY_OF_MONTH,-1);


*/
public class CalendarDemo2 {
    public static void main(String[] args) {
//        int year = 2020;
//        int year = 2016;
//        int year = 2000;
//        int year = 1900;
//        System.out.println(year + "年的二月有" + howManyDaysInFebruary(year) + "天");

        curTimeYesterday();

    }

    public static int howManyDaysInFebruary(int year) {
        Calendar c = Calendar.getInstance();
        c.set(year, 2, 1);
        c.add(Calendar.DAY_OF_MONTH, -1);
        return c.get(Calendar.DAY_OF_MONTH);
    }

    public static void curTimeYesterday() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, -1);

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR);
        int min = c.get(Calendar.MINUTE);
        int sec = c.get(Calendar.SECOND);

        System.out.println("昨天的這個時候是:" + year + "年" + month + "月" + day + "日" + hour + "時" + min + "分" + sec + "秒");
    }
}

/*
練習。給定一個小數。
保留該小數的後兩位。

選作。可以考慮,保留時進行四捨五入。
思路:乘以保留的位數

*/

import java.util.*;

public class MathDemo {
    public static void main(String[] args) {
//        show();
        saveTwo(12.3456, 2, true); // 預期輸出12.35

    }

    public static void saveTwo(double d, int scale, boolean isRound) {
        double base = Math.pow(10, scale);
        double num = isRound ? Math.round(d * base) / base : (int) (d * base) / base;
        System.out.println("num = " + num);
    }


    public static void show() {
        // 返回值默認爲double
        System.out.println(Math.ceil(16.34)); // ceil返回大於指定數據的最小整數
        System.out.println(Math.floor(12.34));// floor返回小於指定數據的最大整數
        System.out.println(Math.round(12.34));// round實現四捨五入
        System.out.println(Math.pow(2, 3));
        System.out.println("..................................");

        // 隨機打印10個[1, 10]範圍的整數
        Random r = new Random();
        for (int x = 0; x < 10; x++) {
            System.out.println(r.nextInt(10) + 1);
        }

    }
}

/*
System:類中的方法和屬性都是靜態的。
out:標準輸出,默認是控制檯。
in:標準輸入,默認是鍵盤。


描述系統一些信息。

獲取系統屬性信息:Properties getProperties();

		//因爲Properties是Hashtable的子類,也就是Map集合的一個子類對象。
		//那麼可以通過map的方法取出該集合中的元素。
		//該集合中存儲都是字符串。沒有泛型定義。
*/

import java.util.*;

public class SystemDemo {
    public static void main(String[] args) {
        Properties prop = System.getProperties();

        // 獲取所有屬性信息
        for (Object obj: prop.keySet()){
            System.out.println(obj+"::"+prop.get(obj));
        }

        // 在系統中自定義一些特有信息
        System.setProperty("myKey", "myValue");

        // 獲取指定屬性信息
        System.out.println("os.name: "+ System.getProperty("os.name"));
        System.out.println("myKey: "+ System.getProperty("myKey"));


    }
}
/*
Runtime對象
該類並沒有提供構造函數。
說明不可以new對象。那麼會直接想到該類中的方法都是靜態的。
發現該類中還有非靜態方法。
說明該類肯定會提供了方法獲取本類對象。而且該方法是靜態的,並返回值類型是本類類型。

由這個特點可以看出該類使用了單例設計模式完成。




該方式是static Runtime getRuntime();
*/
public class RuntimeDemo {
    public static void main(String[] args) throws Exception {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec("notepad.exe RuntimeDemo.java");

        Thread.sleep(4000);
        p.destroy();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章