一、Filewriter與File――-將字符串寫入文本文件
public static void main(String[] args) { File f=new File("C://world.txt");//新建一個文件對象,如果不存在則創建一個該文件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] ;// 所有的內容都讀到此數組之中input.read(b) ;// 讀取內容網絡編程中read 方法會阻塞input.close() ;System.out.println("內容為:" + new String(b)) ;} public static void main(String args[]){File f= new File("C://world.txt") ;// 聲明File對象OutputStream out = null ;// 準備好一個輸出的對象out = new FileOutputStream(f) ;// 通過對像多態性,進行實例化String str = "Hello World!!!" ;// 準備一個字符串byte b[] = str.getBytes() ;// 只能輸出byte數組,所以將字符串變為byte數組out.write(b) ;// 將內容輸出,out.close() ;}三、ObjectOutputStream與ObjectInputStream
ObjectOutputStream將Java對象的基本數據類型和圖形寫入OutputStream。可以使用ObjectInputStream讀取(重構)對象。通過在流中使用文件可以實現對象的持久存儲。
將序列化的對象寫入文件
1、將序列化的對象寫入文件
FileOutputStreamfileStream=newFileOutputStream(“Myobject.ser”);//不存在则自动创建
2、創建ObjectOutputStream
ObjectOutputStreamos=newObjectOutputStream(fileStream);
3、寫入對象
os.writeObject(one);//one是一个对象实例的引用名
4、關閉ObjectOutputStream
os.close
ObjectInputStream用於解序列化
解序列化
1、創建FileInputStream
FileInputStreamfileStream=newFileInputStream(“MyObject.ser”);
2、創建ObjectInputStream
ObjectInputStreamos=newObjectInputStream(fileStream);
3、讀取對象
Objectone=os.readObject();
4、轉換對像類型
Modelelf=(Model)one;//Model是one對象的類名稱
5、關閉ObjectInputStream
os.close();
總結
以上就是本文關於Java將字符串寫入文本文件代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持