java 字串與檔案相互轉換
/**
* Prints some data to a file using a BufferedWriter
*/
private void writeToFile(File file, String txt) {
BufferedWriter bufferedWriter = null;
try {
// Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
// Start writing to the output stream
bufferedWriter.write(txt);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Close the BufferedWriter
if (bufferedWriter != null) {
try {
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public String fileToText(HttpServletRequest request, String pathname) {
if (null == request) {
request = this.request;
}
String contextPath = request.getServletContext().getRealPath("");
File file = new File(contextPath + pathname);
if (!file.exists()) {
return "";
}
return fileToString(file);
}
/**
* Prints some data to a file using a BufferedWriter
*/
private String fileToString(File file) {
BufferedReader bufferedReader = null;
StringBuffer buffer = new StringBuffer();
try {
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while (bufferedReader.readLine() != null) {
buffer.append(bufferedReader.readLine());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return buffer.toString();
}
相關文章
- 陣列與字串方法與相互轉換陣列字串
- JSON字串與HashMap相互轉換JSON字串HashMap
- java 物件與xml相互轉換Java物件XML
- mysql時間與字串之間相互轉換MySql字串
- JavaScript陣列與字串相互轉換 join、splitJavaScript陣列字串
- 記憶體偏移(RVA)與檔案偏移(offset)相互轉換記憶體
- 使用Java完成byte陣列與十六進位制字串相互轉換Java陣列字串
- c語言字串與整形,浮點數...相互轉換C語言字串
- C語言中字串與整數的相互轉換C語言字串
- javascript數字和字串相互轉換JavaScript字串
- 字串和陣列的相互轉換字串陣列
- 字串和數字的相互轉換字串
- C#:檔案、byte[]、Stream相互轉換C#
- Java 檔案換行符識別與轉換Java
- C 語言整數與字串的相互轉換介紹字串
- 轉:java中陣列與List相互轉換的方法Java陣列
- iOS字串和陣列的相互轉換iOS字串陣列
- javascript字串和ascii碼的相互轉換JavaScript字串ASCII
- javascript數字和字串的相互轉換JavaScript字串
- SQL Server 字串和時間相互轉換SQLServer字串
- UIImage與Iplimage相互轉換UI
- SDOM與QDOM相互轉換
- DataTable與List相互轉換
- java物件與json物件間的相互轉換Java物件JSON
- C# 根據KeyEventArgs與組合鍵字串相互轉換C#字串
- javascript中字串和陣列的相互轉換JavaScript字串陣列
- XML與DataSet的相互轉換XML
- 將Schema檔案轉換為Java檔案Java
- json字串和js物件之間相互轉換JSON字串物件
- 判斷迴文串 字串/數字相互轉換字串
- 字串、數值 等型別的相互 安全轉換字串型別
- Python 漢字區位碼、字串 相互轉換Python字串
- Java中 set,list,array(集合與陣列)、Map相互轉換Java陣列
- string與數字相互轉換
- ascii碼與字元的相互轉換ASCII字元
- pandas中dataframe與dict相互轉換
- ASM 檔案與本地檔案的轉換ASM
- Swift3.0語言教程字串與檔案的資料轉換Swift字串