溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Java怎么將字符串寫入文本文件

發(fā)布時(shí)間:2021-04-08 16:50:50 來源:億速云 閱讀:1272 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)使用Java怎么將字符串寫入文本文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

一、Filewriter與File——-將字符串寫入文本文件

public static void main(String[] args) {
     File f=new File("C:\\world.txt");//新建一個(gè)文件對象,如果不存在則創(chuàng)建一個(gè)該文件
     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 ;
	// 準(zhǔn)備好一個(gè)輸入的對象
	try {
		input = new FileInputStream(f) ;
		byte b[] = new byte[1024] ;
		// 所有的內(nèi)容都讀到此數(shù)組之中
		input.read(b) ;
		// 讀取內(nèi)容  網(wǎng)絡(luò)編程中 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 ;
	// 準(zhǔn)備好一個(gè)輸出的對象
	out = new FileOutputStream(f) ;
	// 通過對象多態(tài)性,進(jìn)行實(shí)例化
	String str = "Hello World!!!" ;
	// 準(zhǔn)備一個(gè)字符串
	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))對象。通過在流中使用文件可以實(shí)現(xiàn)對象的持久存儲。

將序列化的對象寫入文件

1、將序列化的對象寫入文件

FileOutputStreamfileStream=newFileOutputStream(“Myobject.ser”);//不存在則自動創(chuàng)建

2、創(chuàng)建ObjectOutputStream

ObjectOutputStreamos=newObjectOutputStream(fileStream);

3、寫入對象

os.writeObject(one);//one是一個(gè)對象實(shí)例的引用名

4、關(guān)閉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、關(guān)閉ObjectInputStream

os.close();

看完上述內(nèi)容,你們對使用Java怎么將字符串寫入文本文件有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI