中化建工北京建設(shè)投資有限公司網(wǎng)站最新的疫情信息
需求 : 如何實(shí)現(xiàn)讀寫文件內(nèi)部的內(nèi)容?流 : 數(shù)據(jù)以先入先出的方式進(jìn)行流動(dòng)相當(dāng)于管道,作用用來傳輸數(shù)據(jù)數(shù)據(jù)源-->流-->目的地流的分類 :流向分 : 以程序?yàn)橹行妮斎肓鬏敵隽鞑僮鲉卧?:字節(jié)流 : 萬能流字符流 : 只能操作純文本文件功能分 :節(jié)點(diǎn)流 : 真實(shí)實(shí)現(xiàn)讀寫的功能流(包裝流|處理流) : 加強(qiáng)節(jié)點(diǎn)流的功能,提高節(jié)點(diǎn)流的性能所有的功能流都需要包裹節(jié)點(diǎn)流進(jìn)行使用所有的分類相輔相成java.io包InputStream : 此抽象類是表示輸入字節(jié)流的所有類的超類。數(shù)據(jù)源 : 文件 | 字節(jié)數(shù)據(jù)文件 : FileInputStream字節(jié)數(shù)據(jù) : ByteArrayInputStreamOutputStream : 此抽象類是表示輸出字節(jié)流的所有類的超類。FileInputStream : 文件字節(jié)輸入流功能分 : 節(jié)點(diǎn)流 操作單元分 : 字節(jié)流 流向分 : 輸入流從文件中讀入數(shù)據(jù)到程序?qū)崿F(xiàn)步驟 :1.與文件建立聯(lián)系 File->數(shù)據(jù)源2.創(chuàng)建文件字節(jié)輸入流->管道3.讀取數(shù)據(jù)4.使用數(shù)據(jù)5.關(guān)閉資源
讀取文件中單個(gè)字符 is.read()
public class IO1 {public static void main(String[] args) throws IOException {File src=new File("D://AAA/test.txt");FileInputStream is= new FileInputStream(src);int num1=is.read();System.out.println((char)num1);System.out.println((char)(is.read()));is.close();}
}
/*字節(jié)流實(shí)現(xiàn)文件拷貝 : *****數(shù)據(jù)源 --文件字節(jié)輸入流 --> 程序 --->文件字節(jié)輸出流--->目的地練習(xí) : 圖片拷貝*/
public class Class005_CopyFile {public static void main(String[] args) {//1.與文件建立聯(lián)系InputStream is = null;OutputStream os = null;try {//2.構(gòu)建流(輸入,輸出)is = new FileInputStream("D://AAA/test.txt");os = new FileOutputStream("D:/test.txt");//3.讀入寫出byte[] car = new byte[1024];int len = -1;while((len=is.read(car))!=-1){os.write(car,0,len);}//4.刷出os.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//5.關(guān)閉(后打開的先關(guān)閉)if(os!=null){try {os.close();} catch (IOException e) {e.printStackTrace();}}if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}}
OutputStream : 此抽象類是表示輸出字節(jié)流的所有類的超類。 根據(jù)目的地選擇具體的子類(節(jié)點(diǎn)流)文件 : FileOutputStream ****字節(jié)數(shù)組 : ByteArrayOutputStreamFileOutputStream : 文件字節(jié)輸出流使用文件字節(jié)輸出流將制定的文本內(nèi)容寫出到文件中 :1.與文件建立聯(lián)系(目的地文件)2.構(gòu)建文件字節(jié)輸出流3.準(zhǔn)備數(shù)據(jù)4.寫出數(shù)據(jù)5.刷出6.關(guān)閉注意 : 輸出流寫出數(shù)據(jù)時(shí),如果源文件存在并且有內(nèi)容,會(huì)默認(rèn)覆蓋,如果想要實(shí)現(xiàn)追加,使用重載構(gòu)造器,boolean append->true追加,false覆蓋(默認(rèn))如果源文件不存在,會(huì)自動(dòng)到目的地所在路徑進(jìn)行創(chuàng)建如果目的地所在路徑不存在,會(huì)拋出異常java.io.FileNotFoundException
public class IO2 {public static void main(String[] args) throws IOException {FileOutputStream os=new FileOutputStream("D:/AAA/AAA.txt",true);int i=97;String str="twlw";os.write(i);os.write(str.getBytes());os.flush();os.close();}
}