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操作文件输出为字符串以及字符串输出为文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下