JavaEEDay22-緩衝流和API


tags:

  • IO流
  • JavaAPI

JavaEEDay22-緩衝流和API

@toc

一、 IO流

分爲:輸入流和輸出流
字節流和字符流

  • 字節流:

    • InputStream
      • FileInputStream
    • OutputStream
      • FileOutputStream
  • 字符流:

    • Reader
      • FileReader
    • Writer
      • FileWriter
  • 注意:

    • 1.使用緩衝效率更高,原因是解決了內存訪問硬盤的次數過多導致的時間上的浪費,通常緩衝流使用的緩衝空間一般都是4KB或者8KB,爲了迎合硬盤讀取的特徵,正是一個扇區的大小;
    • 2.FileWriter 不是直接把數據寫入到磁盤,而是在內存中建立了一個緩衝區,用於保存用戶想要寫入到硬盤的數據,有三種情況纔會真正的寫入數據到硬盤:
      1> 緩衝區滿了
      2> 調用flush,清空緩衝區
      3> FileWriter輸出管道關閉
    • 3.字節流和字符流選擇,
      字節流基本上可以滿足所有的文件內容傳輸需求
      字符流,個人建議 只用來處理記事本可以打開的可視化文件

二、緩衝

昨天學習字符流和字節流的時候,發現如果使用了緩衝,時間效率更高

Sun提供了Java自己的緩衝機制:字節緩衝流和字符緩衝流

—| InputStream 輸入字節流的基類/超類 抽象類
------| FileInputStream 文件操作的字節輸入流
------| BufferedInputStream 緩衝輸入字節流,在緩衝字符流對象中,底層維護了一個8kb緩衝字節數組

  • 構造方法:
    BufferedInputStream(InputStream in);
    BufferedInputStream(InputStream in, int size);
    構造方法中都有一個參數是InputStream, 要求傳入的是InputStream的子類對象(多態),第二個構造方法中多了一個參數是int size ,這個size表示設置緩衝區的大 小, 默認緩衝數組的大小是一個8kb的字節數組
    構造方法中的InputStream是給緩衝流提供讀寫能力的!!!

  • 【記住】
    緩衝流是沒有讀寫能力的,需要對應的字節流或者字符流來提供

  • 使用流程:

    • 1.找到目標文件
    • 2.建立管道
      • a) 首先創建當前文件的InputStream的子類對象,FileInputStream
      • b) 使用InputStream的子類對象,作爲BufferedInputStream構造方法參數,創建緩衝流對象
    • 3.讀取數據
    • 4.關閉資源

(一)輸入字節緩衝

package com.qfedu.a_buffer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class StreamInputBuffered {
	public static void main(String[] args) throws IOException {
		readTest1();
	}
	
	public static void readTest1() throws IOException {
		//1. 找到文件
		File file = new File("C:/aaa/1.txt");
		
		//判斷他是否是一個普通文件,是否存在
		if (!file.exists() || !file.isFile()) {
			throw new FileNotFoundException();
		}
		
		//2. 建立管道
		//創建FileInputStream提供讀寫能力
		FileInputStream fis = new FileInputStream(file);
		
		//利用FileInputStream對象,創建對應的BufferedInputStream
		BufferedInputStream bs = new BufferedInputStream(fis);
		
		//這種方式將上面所有語句合成這一句話,前提是文件必須存在;
		//BufferedInputStream bs2 = new BufferedInputStream(
		//		new FileInputStream(new File("C:/aaa/1.txt")));
		
		//3. 讀取數據(準備一個緩衝數組)
		int length = -1;
		byte[] buffer = new byte[512];
		
		while ((length = bs.read(buffer)) != -1) {
			System.out.println(new String(buffer, 0, length));
		}
		
		
		//4. 關閉資源
		bs.close();
		//在BufferedInputStream的close方法中,該方法會自動關閉創建緩衝流時使用的輸入字節流對象:FileInputStream對象
		//fis.close();//不需要關閉了
	}
}	

(二) 輸出字節緩衝

StreamOutputBuffered.java
能用緩衝就不用字節流

package com.qfedu.a_buffer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class StreamOutputBuffered {
	public static void main(String[] args) throws IOException {
		copyFile();
		//WriteTest();
	}
	
	public static void copyFile() throws IOException {
		//1. 找到源文件
		File srcFile = new File("C:\\Users\\劉曉磊\\Desktop\\頸椎操.avi");
		
		if (!srcFile.exists() || !srcFile.isFile()) {
			throw new FileNotFoundException();
		}
		
		//2. 確定目標文件
		File dstFile = new File("C:\\Users\\劉曉磊\\Desktop\\頸椎操2.avi");
		
		//3. 建立輸入輸出管道
		FileInputStream fis = new FileInputStream(srcFile);
		FileOutputStream fos = new FileOutputStream(dstFile);
		
		//4. 提供對應的緩衝流
		BufferedInputStream bis = new BufferedInputStream(fis);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		
		//5. 讀取數據拷貝
		int length = -1;
		byte[] buffer = new byte[1024 * 8];
		
		while ((length = bis.read(buffer)) != -1) {
			bos.write(buffer, 0, length);
		}
		
		//6. 關閉資源
		bos.close();
		bis.close();
		
	}
	
	public static void WriteTest() throws IOException {
		//1. 確定要操作的文件
		File file = new File("C:/aaa/5.txt");
		
		//2. 建立管道
		//創建FileOutputStream對象,提供讀寫能力
		FileOutputStream fos = new FileOutputStream(file);
		
		//創建BufferedOutputStream對象,用FileOutputStream作爲參數
		BufferedOutputStream bs = new BufferedOutputStream(fos);
		
		//3. 寫入數據
		String str = "今天JD iPad Pro又便宜了一百~~~";
		
		bs.write(str.getBytes());
		
		//4. 關閉資源
		bs.close();
		//fos FileOutputStream不用單獨關閉,緩衝流對象的close會關閉輸出字節流
	}
}

(三)輸入字符緩衝

package com.qfedu.a_buffer;

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

/*
 	BufferedReader 緩衝區是一個char類型數組,數組元素個數爲8192, 佔用空間大小是16KB
 */

public class ReaderBuffered {
	public static void main(String[] args) throws IOException {
		//1. 找到文件
		File file = new File("C:\\Users\\劉曉磊\\Desktop\\稻香.lrc");
		
		//判斷文件是否存在,是否是普通文件
		if (!file.exists() || !file.isFile()) {
			throw new FileNotFoundException();
		}
		
		//2. 建立管道 
		//所有的緩衝流都是沒有讀取能力的,需要提供對應的字符流來提供讀寫能力
		FileReader fr = new FileReader(file);
		BufferedReader br = new BufferedReader(fr);
		
		//3. 讀取文件內容
		String str = null;
		
		while ((str = br.readLine()) != null) { //按行讀取
			System.out.println(str);
		}
		
		//4. 關閉資源
		br.close();
		
	}
}

(四)輸出字符緩衝

package com.qfedu.a_buffer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriterBuffered {
	public static void main(String[] args) throws IOException {
		//1. 確定目標文件
		File file = new File("C:/aaa/6.txt");
		
		//2. 建立管道
		FileWriter fw = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(fw);
		
		//3. 寫入數據
		bw.write("感謝你給我的光榮");
		bw.write("&&&&&&&&&&&");
		bw.newLine(); //換行!!!
		bw.write("*****************");
		
		//4. 關閉資源
		bw.close();
	}
}

三、JavaAPI

(一)String 類型

==和 equals 方法

package com.qfedu.b_javaAPI;

public class Demo1 {
	public static void main(String[] args) {
		String str1 = "David";
		String str5 = "David";
		String str2 = new String(str1);
		String str3 = new String(str1);
		String str4 = new String(str2);
		
		System.out.println("str1 == str5 :" + (str1 == str5)); //true
		System.out.println("str1 == str2 :" + (str1 == str2)); //false
		System.out.println("str2 == str3 :" + (str2 == str3)); //false
		System.out.println("str2 == str4 :" + (str2 == str4)); //false
		System.out.println("str3 == str4 :" + (str3 == str4)); //false
		
		System.out.println("str1.equals(str2):" + str1.equals(str2)); //true
		System.out.println("str1.equals(str3):" + str1.equals(str3)); //true
		System.out.println("str1.equals(str4):" + str1.equals(str4)); //true
		System.out.println("str1.equals(str5):" + str1.equals(str5)); //true
	}
}

(二)String 的方法

package com.qfedu.b_javaAPI;

public class StringMethods {
	public static void main(String[] args) {
		
		// length()  求字符串元素個數,不是佔用的空間
		System.out.println("123".length());  //3
		System.out.println("雷猴~".length()); //3
		
		// charAt(int index); 獲取字符串中的一個字符
		System.out.println("123456789".charAt(5)); //6
		
		//indexOf(int ch); (String str); (char c)
		System.out.println("2345678987654345".indexOf('2')); // 0
		System.out.println("2345678987654345".indexOf("789")); //5
		
		//lastIndexOf()
		System.out.println("23456789876542345".lastIndexOf(2)); //-1 
		//這裏找的是ASCII碼爲2的字符,因爲前32個ASCII碼值不可見
		System.out.println("23456789876542345".lastIndexOf(2)); //13
		System.out.println("23456789876542345".lastIndexOf("345")); //14
		
		//endWith(String str)
		System.out.println("1234567.txt".endsWith("tx")); //false
		
		//contains()
		System.out.println("321321321".contains("21")); //true
		
		//isEmpty()
		System.out.println("1".isEmpty()); //false
		System.out.println("".isEmpty()); //true
		
		//equalsIgnoreCase()
		System.out.println("abc".equals("ABC")); //false
		System.out.println("abc".equalsIgnoreCase("ABC")); //true
		
		//static String valueOf(char[] data);
		char[] arr = {'a','b','c','d','e','f','g'};
		System.out.println(String.valueOf(arr)); //abcdefg
		
		//toCharArray()
		char[] arr2 = "1234567890".toCharArray();
		
		for (char c : arr2) {
			System.out.println(c); 
		}
		//1
		//2
		//......
		
		//replace(char oldChar, char newChar);
		String str = "123456282";
		
		str = str.replace('2', '5');
		System.out.println(str);//"153456285" 因爲有個遍歷,因此是全部調換
		
		
		String lrc = "[00:00.00]侯高俊傑 - 稻香\r\n" + 
				"[00:07.74]\r\n" + 
				"[00:10.58]作詞:周杰倫  作曲:周杰倫\r\n" + 
				"[00:16.05]\r\n" + 
				"[00:31.11]對這個世界如果你有太多的抱怨\r\n" + 
				"[00:34.65]跌倒了  就不敢繼續往前走\r\n" + 
				"[00:37.48]爲什麼  人要這麼的脆弱 墮落\r\n" + 
				"[00:41.61]請你打開電視看看\r\n" + 
				"[00:43.44]多少人爲生命在努力勇敢的走下去\r\n" + 
				"[00:47.37]我們是不是該知足\r\n" + 
				"[00:49.88]珍惜一切 就算沒有擁有";
		//切割字符串
		String[] array = lrc.split("\r\n");
		
		for (String string : array) {
			System.out.println(string);
		}
		
		//trim() 用戶處理前端發送過來數據的多餘空格
		String username = "    lxl";
		System.out.println(username); //     lxl
		username = username.trim();		
		System.out.println(username); //lxl
	}
}

(三)StringBuffer·

package com.qfedu.b_javaAPI;

public class TestStringBuffer {
	public static void main(String[] args) {
		//調用無參構造方法,創建的一個默認字符個數爲16的StringBuffer對象
		StringBuffer stringBuffer = new StringBuffer();
		
		stringBuffer.append("我的家在東北~~~");
		stringBuffer.append('松'); // \40
		
		stringBuffer.insert(10, "花江上啊~~~");
		
		String str = stringBuffer.substring(0, 6);
		
		stringBuffer.delete(0, 6);
		stringBuffer.deleteCharAt(0);
		
		stringBuffer.reverse();
		
		System.out.println(stringBuffer.toString());
		System.out.println(str);
		
		//StringBuilder 是線程不安全的, JDK1.5之後的新特徵,但是效率
		//StringBuffer 是線程安全的,效率低
	}
}

(四)System 裏面的方法

package com.qfedu.b_javaAPI;

import java.util.Properties;

public class TestSystem {
	public static void main(String[] args) {
		//屬性  獲取系統屬性
		Properties ps = System.getProperties(); 
		
		//屬性的展示方式
		ps.list(System.out);
		
		//使用屬性是獲取屬性裏面的內容
		String username = System.getProperty("user.name");
		System.out.println(username);
	}
}

(五)Runtime

package com.qfedu.b_javaAPI;

import java.io.IOException;

public class TsetRuntime {
	public static void main(String[] args) throws IOException, InterruptedException {
		//獲取軟件的運行環境
		Runtime run = Runtime.getRuntime();
		
		System.out.println("當前空餘內存:" + run.freeMemory());
		System.out.println("JVM只能的總內存:" + run.totalMemory());
		System.out.println("JVM能夠使用最大內存:" + run.maxMemory());
		
		Process notepad = run.exec("notepad"); //打開應用程序
		//Process myEclipse = run.exec("C:/MyEclipse Professional 2014/myeclipse.exe");
		
		Thread.sleep(10000);
		
		notepad.destroy();	
	}
}

(六)Date

package com.qfedu.b_javaAPI;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestDate {
	public static void main(String[] args) {
		//Date 封裝了系統的當中的時間類
		Date date = new Date();
		
		//Calender 日曆類 可以直接獲取年月日時分秒
		Calendar c = Calendar.getInstance();
		
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		
		System.out.println(year + ":" + (month + 1) + ":" + day + " " + dayOfWeek 
				+ " " + hour + ":" + minute + ":" + second );
		//格式化顯示
		SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 E  HH:mm:ss");
		System.out.println(sf.format(date));
		
		
	}
}

(七)Math

package com.qfedu.b_javaAPI;

public class TestMath {
	public static void main(String[] args) {
		System.out.println(Math.PI);
		System.out.println(Math.ceil(3.14)); //向上取整 4
		System.out.println(Math.ceil(-3.14)); //向上取整 -3
		
		System.out.println(Math.floor(3.14)); //向下取整 3
		System.out.println(Math.floor(-3.14)); //向下取整 -4
		
		System.out.println(Math.round(15.5));
		System.out.println(Math.round(15.1));
		
		//0 ~ 1 之間的隨機數
		System.out.println(Math.random());
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章