標籤:類對象 char tar ring font 資料 style cep 類執行個體化
FileInputStream
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
-
- public class TestFileInputStream {
- public static void main(String[] args) throws Exception { // 異常拋出, 不處理
- // 第1步: 使用File類找到一個檔案
- File f = new File("c:" + File.separator + "test.txt");// 聲明File 對象
- // 第2步: 通過子類執行個體化父類對象
- InputStream input = null;
- // 準備好一個輸入的對象, 通過對象多態性進行執行個體化
- input = new FileInputStream(f);
- // 第3步:進行讀操作, 所有的內容讀到此數組中
- byte b[] = new byte[1024];
- int len = input.read(b);
- // 第4步:關閉輸入資料流
- input.close();
- // 把byte數組變為字串輸出
- System.out.println("讀入資料的長度:" + len);
- System.out.println("內容為:" + new String(b, 0, len));
- }
- }</span>
FileOutputStream
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStream;
-
- public class TestFileOutputStream {
- public static void main(String[] args) throws Exception { // 異常拋出,不處理
- // 第1步: 使用File類找到一個檔案
- File f = new File("c:" + File.separator + "test.txt"); // 聲明File對象
- // 第2步: 通過子類執行個體化父類對象
- OutputStream out = null;
- // 準備好一個輸出的對象, 通過對象多態性,進行執行個體化
- out = new FileOutputStream(f);
- // 第3步: 進行寫操作, 準備一個字串
- String str = "Hello World!!!";
- // 只能輸出byte數組,所以將字串變為byte數組
- byte b[] = str.getBytes();
- // 將內容輸出,儲存檔案
- out.write(b);
- // 第4步:關閉輸出資料流
- out.close();
- }
- }</span>
FileReader
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileReader;
- import java.io.Reader;
-
- public class TestFileReader {
- public static void main(String[] args) throws Exception { // 異常拋出, 不處理
- // 第1步:使用File類找到一個檔案, 聲明File對象
- File f = new File("d:" + File.separator + "test.txt");
- // 第2步:通過子類執行個體化父類對象
- Reader reader = null;
- // 準備好一個輸入的對象, 通過對象多態性進行執行個體化
- reader = new FileReader(f);
- // 第3步:進行讀操作, 所有的內容讀到此數組中
- char c[] = new char[1024];
- int len = reader.read(c);
- // 第4步:關閉輸入資料流
- reader.close();
- // 把char數組變為字串輸出
- System.out.println("內容為:" + new String(c, 0, len));
- }
- }</span>
FileWriter
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileWriter;
- import java.io.Writer;
-
- public class TestFileWriter {
- public static void main(String[] args) throws Exception { // 異常拋出, 不處理
- // 第1步:使用File類找到一個檔案, 聲明File對象
- File f = new File("c:" + File.separator + "test.txt");
- // 第2步:通過子類執行個體化父類對象
- Writer out = null;
- // 準備好一個輸出的對象, 通過對象多態性, 進行執行個體化
- out = new FileWriter(f);
- // 第3步:進行寫操作, 準備一個字串
- String str = "Hello World!!!";
- out.write(str);
- out.flush();
- // 第4步:關閉輸出資料流
- out.close();
- }
- }</span>
java IO操作:FileInputStream,FileOutputStream,FileReader,FileWriter執行個體