Java操作文件输出为字符串以及字符串输出为文件的方法
文件输出为字符串示例代码:
/** *读取文件为字符串 * *@return */ publicstaticStringreadString(){ Stringstr=""; Filefile=newFile("C:/Users/wan7/Desktop/表单/粗集料试验/粗集料冲击值试验(T0322-2000).html"); try{ FileInputStreamin=newFileInputStream(file); //size为字串的长度,这里一次性读完 intsize=in.available(); byte[]buffer=newbyte[size]; in.read(buffer); in.close(); str=newString(buffer,"utf-8"); }catch(IOExceptione){ returnnull; } returnstr; }
字符串输出为文件示例代码:
/** *输出到文件 */ publicstaticvoidoutFile(Strings){ Filefile=newFile("C:/Users/wan7/Desktop/11111111111.html"); try(FileOutputStreamfop=newFileOutputStream(file)){ //iffiledoesn'texists,thencreateit if(!file.exists()){ file.createNewFile(); } //getthecontentinbytes byte[]contentInBytes=s.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); }catch(IOExceptione){ e.printStackTrace(); } }
以上这篇Java操作文件输出为字符串以及字符串输出为文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。