Java操作文件輸出為字符串以及字符串輸出為文件的方法
更新時間:2018年07月19日 08:51:17 作者:DoubleFJ
今天小編就為大家分享一篇Java操作文件輸出為字符串以及字符串輸出為文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
文件輸出為字符串示例代碼:
/**
* 讀取文件為字符串
*
* @return
*/
public static String readString() {
String str = "";
File file = new File("C:/Users/wan7/Desktop/表單/粗集料試驗/粗集料沖擊值試驗(T0322-2000).html");
try {
FileInputStream in = new FileInputStream(file);
// size 為字串的長度 ,這里一次性讀完
int size = in.available();
byte[] buffer = new byte[size];
in.read(buffer);
in.close();
str = new String(buffer, "utf-8");
} catch (IOException e) {
return null;
}
return str;
}
字符串輸出為文件示例代碼:
/**
* 輸出到文件
*/
public static void outFile(String s) {
File file = new File("C:/Users/wan7/Desktop/11111111111.html");
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = s.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
以上這篇Java操作文件輸出為字符串以及字符串輸出為文件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot系列教程之dubbo和Zookeeper集成方法
這篇文章主要介紹了SpringBoot系列教程之dubbo和Zookeeper集成方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
java并發(fā)編程專題(二)----如何創(chuàng)建并運行java線程
這篇文章主要介紹了java并發(fā)編程如何創(chuàng)建并運行java線程,文中講解非常詳細,示例代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-06-06

