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 祝福语15字以内简短
16 生完孩子祝福语简短
17 幽默祝福语押韵简短
18 家庭生日祝福语大全简短