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操作文件输出为字符串以及字符串输出为文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短