JAVA輸入輸出(.IO)
阿新 • • 發佈:2021-11-22
補:
import java.io.UnsupportedEncodingException; import java.util.*; import java.util.Scanner; public class Main { public static void main(String args[]) throws UnsupportedEncodingException { Scanner sc = new Scanner(System.in); String str="中華人民共和國"; byte[] bytes = str.getBytes("GBK"); //以GBK / GB2312編碼轉化為位元組 System.out.println(bytes.length); //輸出字元長度:14 byte[] bytes = str.getBytes("UTF-8"); //以UTF-8編碼轉化為位元組 System.out.println(bytes.length); //輸出字元長度:21 sc.close(); } }
如果是新建.txt檔案,系統自動在最前面加入幾個位元組
在不同編碼方式下,得到的位元組流不一樣。
流是從源讀取並寫入目標的資料序列。
輸入流用於從源讀取資料。
輸出流用於將資料寫入目標。
流的型別
根據流包含的資料,可以將其分類為:
位元組流
字元流
位元組流(Byte)
JAVA.IO
位元組流用於讀取和寫入單個位元組(8位)的資料。
所有位元組流類都派生自稱為InputStream和OutputStream的基本抽象類。
Java InputStream類
import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class Main { public static void main(String args[]) throws IOException { FileInputStream fis=new FileInputStream("E:\\data.txt"); System.out.println(fis.available());//輸出位元組長度 //一次讀取一個位元組,獲取ASCII值 //如果越界,返回-1 int len=fis.read();//讀取了第1個 System.out.println(len); len=fis.read();//讀取了第2個 System.out.println(len); len=fis.read();//讀取了第3個 System.out.println(len); len=fis.read();//讀取了第4個 System.out.println(len);//如果越界,返回-1 long l1=System.currentTimeMillis(); System.out.println(fis.available());//輸出位元組長度 len=fis.read(); while(len!=-1) { System.out.println(len); len=fis.read(); } long l2=System.currentTimeMillis(); System.out.println(l2-l1);//計算讀取時間 fis.close(); } }
read(bytes)//效率比較高
read(bytes,int begin,int end)//當有需要固定某些字元時候才使用,不常用
import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class Main { public static void main(String args[]) throws IOException { FileInputStream fis2=new FileInputStream("E:\\data.txt"); byte[] bytes=new byte[2]; int le=fis2.read(bytes); System.out.println(le); System.out.println(Arrays.toString(bytes)); bytes=new byte[2]; le=fis2.read(bytes); System.out.println(le); System.out.println(Arrays.toString(bytes)); bytes=new byte[2]; le=fis2.read(bytes); System.out.println(le); System.out.println(Arrays.toString(bytes)); bytes=new byte[2]; le=fis2.read(bytes); System.out.println(le); System.out.println(Arrays.toString(bytes)); fis2.close(); System.out.println("--------------------------"); FileInputStream fis3=new FileInputStream("E:\\data.txt"); byte[] bytes2=new byte[2]; int le2=fis3.read(bytes2); while(le2!=-1) { // System.out.println(le2); //System.out.println(Arrays.toString(bytes2)); String strr=new String(bytes2,0,le2); System.out.println(strr); le2=fis3.read(bytes2); } //再簡化 while((fis3.read(bytes2)!=-1) { String strr=new String(bytes2,0,le2); System.out.println(strr); } fis3.close(); } }
Java OutputStream類
字元流(Character )
字元流用於讀取和寫入單個數據字元。
所有字元流類都派生自基本抽象類Reader和Writer。
Java Reader類
Java Writer類