Java將字符串寫入文本文件代碼示例
一、Filewriter與File——-將字符串寫入文本文件
public static void main(String[] args) { File f=new File("C:\\world.txt");//新建一個文件對象,如果不存在則創(chuàng)建一個該文件 FileWriter fw; try { fw=new FileWriter(f); String str="hello world"; fw.write(str);//將字符串寫入到指定的路徑下的文件中 fw.close(); } catch (IOException e) { e.printStackTrace(); } }
二、InputStream與OutputStream 輸入與輸出串流
public static void main(String args[]){ File f= new File("C:\\world.txt") ; InputStream input = null ; // 準備好一個輸入的對象 try { input = new FileInputStream(f) ; byte b[] = new byte[1024] ; // 所有的內(nèi)容都讀到此數(shù)組之中 input.read(b) ; // 讀取內(nèi)容 網(wǎng)絡編程中 read 方法會阻塞 input.close() ; System.out.println("內(nèi)容為:" + new String(b)) ; }
public static void main(String args[]){ File f= new File("C:\\world.txt") ; // 聲明File對象 OutputStream out = null ; // 準備好一個輸出的對象 out = new FileOutputStream(f) ; // 通過對象多態(tài)性,進行實例化 String str = "Hello World!!!" ; // 準備一個字符串 byte b[] = str.getBytes() ; // 只能輸出byte數(shù)組,所以將字符串變?yōu)閎yte數(shù)組 out.write(b) ; // 將內(nèi)容輸出, out.close() ; }
三、ObjectOutputStream與ObjectInputStream
ObjectOutputStream將Java對象的基本數(shù)據(jù)類型和圖形寫入OutputStream??梢允褂肙bjectInputStream讀取(重構(gòu))對象。通過在流中使用文件可以實現(xiàn)對象的持久存儲。
將序列化的對象寫入文件
1、將序列化的對象寫入文件
FileOutputStreamfileStream=newFileOutputStream(“Myobject.ser”);//不存在則自動創(chuàng)建
2、創(chuàng)建ObjectOutputStream
ObjectOutputStreamos=newObjectOutputStream(fileStream);
3、寫入對象
os.writeObject(one);//one是一個對象實例的引用名
4、關閉ObjectOutputStream
os.close
ObjectInputStream用于解序列化
解序列化
1、創(chuàng)建FileInputStream
FileInputStreamfileStream=newFileInputStream(“MyObject.ser”);
2、創(chuàng)建ObjectInputStream
ObjectInputStreamos=newObjectInputStream(fileStream);
3、讀取對象
Objectone=os.readObject();
4、轉(zhuǎn)換對象類型
Modelelf=(Model)one;//Model是one對象的類名稱
5、關閉ObjectInputStream
os.close();
總結(jié)
以上就是本文關于Java將字符串寫入文本文件代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持
相關文章
mybatis-plus 處理大數(shù)據(jù)插入太慢的解決
這篇文章主要介紹了mybatis-plus 處理大數(shù)據(jù)插入太慢的解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12httpclient staleConnectionCheckEnabled獲取連接流程解析
這篇文章主要為大家介紹了httpclient staleConnectionCheckEnabled獲取連接流程示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11