Java的輸入輸出流
阿新 • • 發佈:2018-01-24
ava hello 寫入 數組長度 byte[] txt 數據讀取 抽象 清空
概述:
java中的io流主劃分輸入流和輸出流;其中又各自分有字節流和字符流;兩者的差別主要是在於讀入/寫出的單位大小不同;由於java采用的是GBK編碼格式,因而一個字符占用2個字節,即字符流是16位,字節流是8位。還有一種劃分就是:節點流和處理流;節點流:直接與數據源連接進行傳輸數據處理流:就是非直接,而是對節點流進行封裝等使用(是一種比較好的方法)!!!!
輸入流有2個抽象基類:InputStream和Reader 輸出流有2個抽象基類:OutputStream和Writer;其中,InputStream和OutputStream是屬於字節流的8位Writer&Reader是屬於字符流(2個字節 16位)
//檢測InputStream流的read(byte[] b,int off,int len)方法
1 import java.io.*;
2
3 public class hellojava{
4 public static void main(String[] args) throws IOException {
5 try{
6 FileInputStream fin1=new FileInputStream("/home/kylin/Desktop/操作PG數據庫.txt");
7 byte []buf1=new byte[1024];
8 int HasRead1=0;
9 while((HasRead1=fin1.read(buf1,5,1019))>0){
10 System.out.println("HasRead1:"+HasRead1);
11 System.out.println(new String(buf1,5,HasRead1));
12 }
13 }
14 catch(IOException ex){
15 ex.printStackTrace();
16 }
17 }
18 }
//使用try catch會自動的調用 close(),而調用close()又會自動的調用flush();所以使用try catch方式可以自動的關閉IO流
// read(buf,off,len) 這裏的len長度最大值一定是要小於 buf.length-off
//註意:由於java采取的是GBK編碼,因而在讀取的長度的設置(數組長度的設置上)要盡可能的大一些,不然可能會因為長度不夠而亂碼
//檢測 Reader抽象基類中的read(char []b,int off,int len)方法;和上述方法的效果是差不多一致的
1 import java.io.*;
2
3 public class hellojava{
4 public static void main(String[] args)throws IOException {
5 try{
6 FileReader fin=new FileReader("/home/qilin/Desktop/操作PG數據庫.txt");
7 int HasRead=0;
8 char []buf=new char[1024];
9 while((HasRead=fin.read(buf,5,100))>0){
10 System.out.println("HasRead:"+HasRead);
11 System.out.println(new String(buf, 5,HasRead));
12 }
13 }
14 catch(IOException ex){
15 ex.printStackTrace();
16 }
17 }
18 }
1 import java.io.*;
2
3 //嘗試把文件A中的數據讀取,然後寫入到另外一個文件B中
4 public class hellojava{
5 public static void main(String[] args) {
6 try{
7 FileInputStream fin=new FileInputStream("/home/qilin/Desktop/操作PG數據庫.txt");
8 FileOutputStream fout=new FileOutputStream("/home/qilin/Desktop/hello1.txt");
9 int hasRead=0;
10 byte []buf=new byte[1024];
11 //寫入到buf數組中
12 while((hasRead=fin.read(buf))>0){
13 //從buf數組中輸出到hello1.txt文件中
14 fout.write(buf, 0, hasRead);
15 }
16 }
17 catch(IOException ex){
18 ex.printStackTrace();
19 }
20
21 }
22 }
import java.io.*;
//當我沒有清空緩沖區、和關閉流的時候,即使可以運行;但是並不會寫到文件中!
//使用 try catch 也不會寫入到文件中,只有當自己顯式的清空緩沖區和關閉流才會成功寫入;難道寫的時候調用try catch不會關閉流??
//測試使用Writer的write,把字符串寫入到文件中
public class hellojava{
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("/home/qilin/Desktop/hello3.txt");
fw.write("大家好\n");
// fw.write("新年快樂\n",0,6); 拋出異常,因為實際並沒這麽長
fw.write("新年快樂", 2, 2);
fw.flush(); //緩沖區寫到物理節點
fw.close(); //關閉
}
}
//看來還是自己手動來關閉吧~
Java的輸入輸出流