標籤:內容 ati void print 分隔字元 imp 知識點 str exception
package zdbIO;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamDemo1 {
/**
* @throws IOException
* @throws IOException
*
*/
下邊使用outputStream位元組輸出資料流進行寫操作
public static void main(String[] args) throws IOException{
/**
* 使用IO流的具體步驟:
* 1.使用file找到要操作的檔案
* 2.(使用位元組流或字元流的子類來執行個體化inputStream、outStream、reader、writer)
* 3.進行讀寫操作
* 4.關閉流,除BufferedReader例外
*/
File file = new File("f:"+File.separator+"zdb1.txt");//使用file找到要操作的檔案
OutputStream out = null;
out = new FileOutputStream(file,true);//使用OutputStream的子類進行執行個體化
String str = "XXX的十年人生規劃,一定要有個計劃這樣你的人生才會有明確的方向 不至於迷失。";//要輸出的資訊
byte b[] = str.getBytes();//將str變為byte數組
out.write(b);//寫入資料
out.close();//關閉流
}
}
下邊使用inputStream位元組流進行讀操作:
package zdbIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* 通過inputStream位元組流來進行讀操作
*
*/
public class InputStreamDemo {
public static void main(String[] args) throws Exception {
//注意此檔案必須存在否則會發生java.io.FileNotFoundException異常
//File.separator表示分隔字元,其中在Windows中表示\,在unix表示/,這樣可以跨平台
File file = new File("f:"+File.separator+"zdb1.txt");
InputStream input = null;
input = new FileInputStream(file);
byte b[] = new byte[1024];//開闢一塊記憶體用來儲存讀取的內容
int len = input.read(b);//將檔案讀到字元數組中
//其中new String(byte[]bytes,int offset,int length),
//表示將建立一個字串,從offset為開始,長度為length
System.out.println(new String(b,0,len));
input.close();
}
}
java中IO流相關知識點