更新時(shí)間:2020-08-24 16:58:56 來源:動(dòng)力節(jié)點(diǎn) 瀏覽2570次
java文件輸出流是一種用于處理原始二進(jìn)制數(shù)據(jù)的字節(jié)流類。為了將數(shù)據(jù)寫入到文件中,必須將數(shù)據(jù)轉(zhuǎn)換為字節(jié),并保存到文件。
package?com.yiibai.io;
import?java.io.File;
import?java.io.FileOutputStream;
import?
java.io.IOException;
public?class?WriteFileExample?{
?public?static?void?main(String[]?args)?
{
??FileOutputStream?fop?=?null;
??File?file;
??String?content?=?"This?is?
the?text?content";
??try?{
???file?=?new?File("c:/newfile.txt");
???fop?=?new?
FileOutputStream(file);
???//?if?file?doesnt?exists,?then?create?it
???if?(!file.exists())?
{
????file.createNewFile();
???}
???//?get?the?content?in?bytes
???byte[]?contentInBytes?=?
content.getBytes();
???fop.write(contentInBytes);
???fop.flush();
???fop.close();
???System.out.println("Done");
??}?catch?(IOException?e)?{
???e.printStackTrace();
??}?finally?{
???try?{
????if?(fop?!=?null)?{
?????fop.close();
????}
???}?catch?
(IOException?e)?{
????e.printStackTrace();
???}
??}
?}
}
//更新的JDK7例如,使用新的“嘗試資源關(guān)閉”的方法來輕松處理文件。
package?
com.yiibai.io;
import?java.io.File;
import?java.io.FileOutputStream;
import?
java.io.IOException;
public?class?WriteFileExample?{
?public?static?void?main(String[]?args)?
{
??File?file?=?new?File("c:/newfile.txt");
??String?content?=?"This?is?the?
text?content";
??try?(FileOutputStream?fop?=?new?FileOutputStream(file))?{
???//?if?file?doesn't?exists,?then?create?it
???if?(!file.exists())?
{
????file.createNewFile();
???}
???//?get?the?content?in?bytes
???byte[]?contentInBytes?=?
content.getBytes();
???fop.write(contentInBytes);
???fop.flush();
???fop.close();
???System.out.println("Done");
??}?catch?(IOException?e)?{
???e.printStackTrace();
??}
?}
}
以上就是動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java文件輸出流寫文件的幾種方法”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)