文件輸出為字符串示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/** * 讀取文件為字符串 * * @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; } |
字符串輸出為文件示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * 輸出到文件 */ 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操作文件輸出為字符串以及字符串輸出為文件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/ffj0721/article/details/73996576