您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)如何使用java中OutStream()向文件中寫入內(nèi)容,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
使用java中OutStream()向文件中寫入內(nèi)容
package Stream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class OutStreamDemo01 { public static void main(String[] args) { //定義文件路徑,沒有該文件會自動創(chuàng)建,如果路徑有文件夾,一定要有,不會自動創(chuàng)建文件夾 String filename = "e:"+File.separator+"a"+File.separator+"b.txt"; File file = new File(filename); String str = "這些都將寫入文件中"; byte[] b = str.getBytes(); //將字符串轉(zhuǎn)換成字節(jié)數(shù) OutputStream out = null; try { out = new FileOutputStream(file); //實例化OutpurStream }catch(FileNotFoundException e){ e.printStackTrace(); } //寫入 try { out.write(b); //寫入 out.close(); //關(guān)閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
使用InputStream()讀取文件中的內(nèi)容:
package Stream; import java.io.*;; public class InputStreamDemo01 { public static void main(String[] args) { File file = new File("e:"+File.separator+"a"+File.separator+"b.txt"); byte[] b = new byte[(int)file.length()];//定義byte字節(jié)的長度 InputStream in = null; int len = 0; try { //處理異常 in = new FileInputStream(file); //實例化FileInputstream類 } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); //輸出異常 } try { len = in.read(b); //讀取指定文件的內(nèi)容 in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(new String(b,0,len));//將字節(jié)數(shù)組轉(zhuǎn)化成字符串輸出指定文件從0開始到len字節(jié)結(jié)束 } }
關(guān)于“如何使用java中OutStream()向文件中寫入內(nèi)容”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。