一:輸入和輸出概念
輸入流(inputstream):對於java程序來說,從程序寫入文件叫做輸出。
輸出流(outputstream):對於java程序來說,從文件讀取數據,到java程序叫做輸入。
二:字節流輸出(outputstream)
該類是抽象類,public abstract class OutputStream extends Object implements Closeable, Flushable
所以如果想調用他的方法,需要通過子類來進行調用,該類的操作是字節,所以叫做字節輸出流
操作文件可以是任意文件。
1:方法:
1: close()關閉字節輸出流,釋放資源,類似python中操作文件,最后需要close一樣。
2:write()該方法為重載方法,將相應的內容寫入文件中。
3:flush()是將緩存的數據刷入永久存儲(文件)中。
:2:查看其實現類:
實現類有如下:
我先來使用:FileOutoutStream類。
public class FileOutputStream
extends OutputStream
構造器:
如上構造器,通過綁定文件句柄。來實現文件操作。
1 package test14; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.OutputStream; 7 8 public class OutputStreamDemon { 9 public static void main(String...args){ 10 11 } 12 public static void outputStrem(File file) throws FileNotFoundException{ 13 FileOutputStream fps=new FileOutputStream(file); 14 FileOutputStream fps1=new FileOutputStream("c:\\new"); 15 16 } 17 }
其中append參數的含義:
如果寫true表示在文本的最后追加寫入。不是覆蓋寫入!
1 FileOutputStream fps1=new FileOutputStream("c:\\new",true);
1 package test14; 2 3 import java.io.*; 4 5 public class OutputStreamDemon { 6 public static void main(String...args){ 7 File file=new File("c:\\new"); 8 try{ 9 outputStrem(file); 10 }catch (IOException ex){ 11 System.out.print(ex); 12 } 13 14 15 } 16 public static void outputStrem(File file) throws FileNotFoundException,IOException{ 17 OutputStream fps=new FileOutputStream(file); 18 OutputStream fps1=new FileOutputStream("c:\\new",true);//append 默認寫true 表示寫入內容追加到文件末尾。 19 byte[] w_con=new byte[]{'o','k'};//寫入文件內容需要字節數組。 20 fps1.write(w_con); 21 fps1.write(65);//寫的數字轉換成字母。 22 fps1.close();//關閉文件句柄 釋放資源. 23 24 } 25 }
輸出結果:
換行:
1 byte[] w_con=new byte[]{'o','\n','k'};//寫入文件內容需要字節數組。
在寫入字節的時候,寫入的內容會對比ASCII表,轉換成對應的值寫入文件。
1 package Fileout_Demo; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 public class Fieloutstream_Demo { 8 public static void main (String...args){ 9 try { 10 write_Test(); 11 }catch (IOException e){ 12 System.out.print(e); 13 } 14 15 } 16 17 public static void write_Test() throws IOException{ 18 File f=new File("c:/tmp.txt"); 19 FileOutputStream fs=new FileOutputStream(f); 20 fs.write("ok".getBytes());//將字符串轉換成對應的字節數組。如果是數字的話會按照assic表來寫入對應的值。 21 fs.close(); 22 } 23 24 }