字節流輸出
OutputStream :寫入。這是抽象類,是輸出字節流的超類,操作數據的都是字節
FileOutputStream是OutputStream可用來寫入數據到文件的子類,
FileOutputStream構造方法,如果指定的文件不存在,他會創建一個,如果指定的文件存在,他會創建並覆蓋
1 public static void main(String[] args) throws FileNotFoundException { 2 File f = new File("E:\\java學習\\6月15號\\a.txt"); //創建File對象路徑
3 FileOutputStream f1 = new FileOutputStream(f); //創建一個a.txt文件
FileOutputStream f = new FileOutputStream("E:\\java學習\\6月15號\\a.txt"); //調用FileOutPutStream(String name)構造方法
1 FileOutputStream f = new FileOutputStream("E:\\java學習\\6月15號\\a.txt"); 2 byte[] by ={97,98,99,100}; 創建一個byte【】 數組,調用write(byte【】 b)方法就把字節寫入a.txt 3 f.write(by);
字節輸入流
InputStream :讀取。是 字節輸入流的超類,這是一個抽象方法,定義了對數據輸入的方式
FileInputStream 是InputStram的子類,實現了字節輸入
1 public class Tese { 2 3 public static void main(String[] args) throws IOException { 4 File f = new File("E:\\java學習\\6月25號\\a.txt"); 5 FileInputStream f2 =new FileInputStream(f); 6 byte[] by = new byte[1024]; 7 int len =0; 用來接收字節長度,如果不等於-1,就一直往下讀取 8 while((len=f2.read())!=-1){ 9 System.out.print((char)len); 10 } 11 f2.close(); 12 } 13 }
復制文件
先讀取后寫入
public class Tese { public static void main(String[] args) throws IOException { File f = new File("E:\\java學習\\6月25號\\a.txt"); 創建讀取的對象文件,源文件 FileInputStream f2 =new FileInputStream(f); FileOutputStream f3 =new FileOutputStream("E:\\java學習\\6月25號\\b.txt"); 創建接收的文件,目的文件 byte[] by = new byte[1024]; int len =0; while((len=f2.read(by))!=-1){ 當len不等於-1,就一直寫入 f3.write(by, 0, len); 讀取by數組,從第0位開始,到-1位結束的 } f2.close(); f3.close(); } }