package test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * 使用FileInputStream讀取文件 * 使用FileOutputStream寫入文件 * @author 尹濤 * */ public class Test { public static void main(String[] args) throws IOException { //文件地址路徑 String path="D:\\test\\test.txt"; //要寫入的內容 String str="使用FileOutputStream寫入文件"; //輸出流對象 FileOutputStream fos=null; //創建文件輸入流對象 FileInputStream fis=null; try { //實例化輸出流對象參數文件路徑地址 fos=new FileOutputStream(path); //將要寫入內容的轉換為byte數組 byte[] but=str.getBytes(); //寫入文件 參數(byte數組 從0開始寫,長度為數組長度) fos.write(but, 0, but.length); //實例化輸出流對象參數讀取的文件路徑地址 fis=new FileInputStream(path); //將讀取到文件轉存儲到byte數組 參數為文件的字節長度 byte[] inputStream=new byte[fis.available()]; //循環讀取 while (fis.read(inputStream)!=-1) { //將byte數組中的內容轉換為String內容字符串輸出 String s = new String(inputStream, 0, inputStream.length); System.out.println(s); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally{ if(fos!=null){ fos.close(); //關閉流對象 } if(fis!=null){ fis.close(); //關閉流對象 } } } }
java的輸出流主要由OutputStream和Writer作為基類,而輸入流主要由InputStream和Reader作為基類.
字節輸入流InputStream讀取數據常用的方法
int read() 讀取一個字節數據
int read(byte[] b) 將數據讀取到字節數組中
int read(byte[]b,int off, int len) 從輸入流中讀取最多len長度字節,保存到字節數組b中,保存位置從off開始
void close() 關閉輸入流
int avaiable() 返回輸入流讀取的估計字節數
字節輸入流OutputStream常用的方法
void write(int c) 寫入一個字節數據
void write(btye[] buf) 寫入數組buf的所有字節
void write(byte[]b ,int off,int len) 將字節數組中從off位置開始,長度為len的字節數據輸出到輸出流中
void close() 關閉流對象
package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * 使用字符流寫入文本 * 使用字符流讀取文本 * @author 尹濤 * */ public class Test1 { public static void main(String[] args) throws IOException { //文件地址路徑 String path="D:\\test\\test.txt"; //創建FileReader對象 FileReader fr=null; //創建BufferedReader BufferedReader br=null; //創建FileWriter FileWriter fw=null; //創建BufferedWriter對象 BufferedWriter bw=null; try { //實例化FileReader對象 fr=new FileReader(path); //實例化BufferedReader對象 br=new BufferedReader(fr); //實例化FileWriter對象 參數要寫入的地址 fw=new FileWriter("E:\\test\\test.txt"); //實例化BufferedWriter 對象 bw=new BufferedWriter(fw); //對取一行數據 String line=""; //循環讀取 while ((line=br.readLine())!=null) { System.out.println(line); bw.write(line); //將讀取到循環寫入 bw.newLine(); //換行 } } catch (FileNotFoundException e) { e.printStackTrace(); }finally{
//關閉順序為先開的后關 bw.close(); fw.close(); br.close(); fr.close(); } }
Reader類是讀取字節流的抽象類常用方法有
int read() 從輸入留讀取單個字符
int read(byte[] b) 從輸入流中讀取b.length 長度的字符保存帶數組b中 返回實際讀取的字符數
read(byte[] b,int off,int len) 從輸入流讀取最多len的長度字符,保存到字符數組b中,保存位置從off位置開始.返回實際讀取的字符長度
void close() 關閉流
Writer類是向文件寫入數據的字符流,常用方法有
writer(String str) 將str字符串里包含的字符輸出到指定的輸出流中
writer(String str,int off,int len) 將str字符串里從off位置開始長度為len的字符輸出到輸出流中
void close() 關閉流對象
void flush() 刷新輸出流