IT十八掌作業_java基礎第十四天_IO

1.定義函數,輸出一個byte的二進制字符串。

2.定義工具類,完成int數和byte[]之間的相互轉換。

3.闡述IO流。

    輸入輸出流

    字符字節流

    緩衝和非緩衝流

    轉換流.

4.通過File對象打印輸出指定路徑下的整個目錄樹結構。

5.完成文件夾複製。


---------------------------------------------

1.

package com.it18zhang.day14;


public class ByteToBin {

    public static void main(String[] args) {

        byte b1 = -128;

        byte b2 = 127;

        byte b3 = 0;

        byte b4 = -1;

        byte b5 = 1;

        System.out.println("-128的二進制字符串" + printByteBinary(b1));

        System.out.println("127的二進制字符串" + printByteBinary(b2));

        System.out.println("0的二進制字符串" + printByteBinary(b3));

        System.out.println("-1的二進制字符串" + printByteBinary(b4));

        System.out.println("1的二進制字符串" + printByteBinary(b5));

    }




    /**

     * 輸出一個byte的二進制字符串

     * 

     * @param b

     * @return binary string

     */

    public static String printByteBinary(byte b) {

        // 先將byte隱式轉換成int數,

        int num = b;

        // 然後將int數與256進行位或運算,將前24位都換成1。

        num |= 256;

        // 通過Integer工具類的toBinaryString打印出int的二進制字符串。

        String str = Integer.toBinaryString(num);

        int len = str.length();

        // 截取字符串的最後8位字符

        return str.substring(len - 8, len);


    }


}




2.

package com.it18zhang;

/**

 *定義工具類,完成int到byte[]之間轉換

 */

public class BinToByteUtils {


public static void main(String[] args) {

//int轉換成字節數組

int num = -400;

byte[] bytes = intToByteArray(num);

for(int i = 0; i<bytes.length ; i++){

System.out.println("index " + i +" = "+bytes[i]);

}

System.out.println("----------------------");

//字節數組轉int

System.out.println(byteToIntArray(bytes));

}

/**

* 將int整數轉換成字節數組

*/

public static byte[] intToByteArray(int param){

//一個int四個字節,一個字節8位

byte[] byteArray = new byte[4];

byte b0 = (byte)param;

byte b1 = (byte)(param >> 8);

byte b2 = (byte)(param >> 16);

byte b3 = (byte)(param >> 24);

byteArray[0] = b0;

byteArray[1] = b1;

byteArray[2] = b2;

byteArray[3] = b3;

return byteArray;

}

/**

* 將字節數組轉換成int整數

*/

public static int byteToIntArray(byte[] arr){

int num =0;

if(arr.length == 4){

//將最後一個字節左移24位,稱爲最高位

int num3 = arr[3] << 24;

//爲了消除負數類型提升後前面多餘的1,採用&0xFF保留有效8位

int num2 = (arr[2] & 0xFF) <<16;

int num1 = (arr[1] & 0xFF)<<8;

int num0 = (arr[0] & 0xFF) <<0;

num = num3 | num2 | num1 | num0;

}

return num;

}

}


3.闡述IO流。

    輸入輸出流

    字符字節流

    緩衝和非緩衝流

    轉換流.

答:

流是一組有順序的,有起點和終點的字節集合,是對數據傳輸的總稱或抽象。即數據在兩設備間的傳輸稱爲流,

IO流的本質是數據傳輸,根據數據傳輸特性將流抽象爲各種類,方便更直觀的進行數據操作。 

按數據流向分爲輸入輸出流,主要有InputStream和OutputStream兩個類及其子類

按數據類型分爲字符字節流,主要有Reader和Writer兩個類及其子類

爲了提高IO效率,引入了緩衝技術,通過緩衝流批量讀寫。而非緩衝流是通過一個一個字節或者字符進行讀寫。

轉換流是指字節流和字符流之間的轉換,主要包括InputStreamReader和OutputStreamWriter兩個類。



4.


package com.it18zhang;


import java.io.File;


/**

 * 通過File對象打印輸出指定路徑下的整個目錄樹結構。

 * 

 */

public class TreeDirectory {


    // 文件所在的層數

    private int fileLevel;




    public static void main(String[] args) {

        TreeDirectory rd = new TreeDirectory();

        String dirPath = "C:/Program Files";

        rd.printDir(dirPath);

        System.out.println("--------------");

        rd.readFile(dirPath);

    }




    /**

     * 生成輸出格式

     * 

     * @param name

     *            輸出的文件名或目錄名

     * @param level

     *            輸出的文件名或者目錄名所在的層次

     * @return 輸出的字符串

     */


    public String createPrintStr(String name, int level) {

        // 輸出的前綴

        String printStr = "";

        // 按層次進行縮進

        for (int i = 0; i < level; i++) {

            printStr = printStr + "   ";

        }

        printStr = printStr + "--" + name;

        return printStr;

    }




    /**

     * 輸出初始給定的目錄

     * 

     * @param dirPath

     *            給定的目錄

     */

    public void printDir(String dirPath) {

        // 將給定的目錄進行分割

        String[] dirNameList = dirPath.split("\\\\");

        // 設定文件level的base

        fileLevel = dirNameList.length;

        // 按格式輸出

        for (int i = 0; i < dirNameList.length; i++) {

            System.out.println(createPrintStr(dirNameList[i], i));

        }

    }




    /**

     * 輸出給定目錄下的文件,包括子目錄中的文件

     * 

     * @param dirPath

     *            給定的目錄

     */

    public void readFile(String dirPath) {

        // 建立當前目錄中文件的File對象

        File file = new File(dirPath);

        // 取得代表目錄中所有文件的File對象數組

        File[] list = file.listFiles();

        // 遍歷file數組

        if (list != null) {

            for (int i = 0; i < list.length; i++) {

                if (list[i].isDirectory()) {

                    System.out.println(createPrintStr(list[i].getName(), fileLevel));

                    fileLevel++;

                    // 遞歸子目錄

                    readFile(list[i].getPath());

                    fileLevel--;

                }

            }

        }

    }

}

5.

package com.it18zhang;



import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;


public class DirCopy {


public static void main(String[] args) {

copyDir("d:/a", "d:/b");

}


/**

* 複製文件夾

*/

private static void copyDir(String srcRoot, String srcDir, String destDir) {

if (srcRoot == null) {

srcRoot = srcDir;

}

// 源文件夾

File srcFile = new File(srcDir);

// 目標文件夾

File destFile = new File(destDir);


// 判斷srcFile有效性

if (srcFile == null || !srcFile.exists()) {

return;

}

// 創建目標文件夾

if (!destFile.exists()) {

destFile.mkdirs();

}


// 判斷是否文件?

if (srcFile.isFile()) {

String absPath = srcFile.getAbsolutePath();

// 取出上級目錄 d:

String parentDir = new File(srcRoot).getParent();


// 取出相對的路徑a

String relPath = absPath.substring(parentDir.length());

File destFile2 = new File(destDir, relPath);

// 拷貝文件

copyFile(srcRoot, srcFile.getAbsolutePath(), destDir);

}

// 目錄

else {

File[] children = srcFile.listFiles();

if (children != null) {

for (File f : children) {

copyDir(srcRoot, f.getAbsolutePath(), destDir);

}

}

}

}


public static void copyDir(String srcDir, String destDir) {

copyDir(srcDir, srcDir, destDir);

}


/**

* 複製文件

*/

public static void copyFile(String srcRoot, String path, String destDir) {

try {


// 準備目錄

// 取出相對的路徑

String tmp = path.substring(srcRoot.length());

//獲取目標文件的父目錄絕對路徑

String folder = new File(destDir, tmp).getParentFile().getAbsolutePath();

System.out.println(folder);

File destFolder = new File(folder);

destFolder.mkdirs();


File f = new File(path);

// fis

FileInputStream fis = new FileInputStream(path);


String newDestpath = null;

// 文件輸出流

FileOutputStream fos = new FileOutputStream(new File(destFolder,

new File(path).getName()));


// 流的對拷貝

byte[] buf = new byte[1024];

int len = 0;

while ((len = fis.read(buf)) != -1) {

fos.write(buf, 0, len);

}

fis.close();

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}


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