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 红包祝福语简短10字
18 周六早晨祝福语简短