更新時間:2020-08-24 16:58:56 來源:動力節點 瀏覽2425次
java文件輸出流是一種用于處理原始二進制數據的字節流類。為了將數據寫入到文件中,必須將數據轉換為字節,并保存到文件。
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例如,使用新的“嘗試資源關閉”的方法來輕松處理文件。
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();
??}
?}
}
以上就是動力節點java培訓機構的小編針對“Java文件輸出流寫文件的幾種方法”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習