更新時間:2020-08-24 16:58:56 來源:動力節(jié)點 瀏覽2486次
java文件輸出流是一種用于處理原始二進制數(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例如,使用新的“嘗試資源關閉”的方法來輕松處理文件。
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();
??}
?}
}
以上就是動力節(jié)點java培訓機構(gòu)的小編針對“Java文件輸出流寫文件的幾種方法”的內(nèi)容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務。