方式一
/**
以字節為單位讀取文件,常用于讀二進制文件,如圖片、聲音、影像等文件。
當然也是可以讀字符串的。
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/* 貌似是說網絡環境中比較復雜,每次傳過來的字符是定長的,用這種方式?*/ public string readstring1() { try { //fileinputstream 用于讀取諸如圖像數據之類的原始字節流。要讀取字符流,請考慮使用 filereader。 fileinputstream instream= this .openfileinput(file_name); bytearrayoutputstream bos = new bytearrayoutputstream(); byte [] buffer= new byte [ 1024 ]; int length=- 1 ; while ( (length = instream.read(buffer) != - 1 ) { bos.write(buffer, 0 ,length); // .write方法 sdk 的解釋是 writes count bytes from the byte array buffer starting at offset index to this stream. // 當流關閉以后內容依然存在 } bos.close(); instream.close(); return bos.tostring(); // 為什么不一次性把buffer得大小取出來呢?為什么還要寫入到bos中呢? return new(buffer,"utf-8") 不更好么? // return new string(bos.tobytearray(),"utf-8"); } } |
方式二
// 有人說了 filereader 讀字符串更好,那么就用filereader吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 每次讀一個是不是效率有點低了? private static string readstring2() { stringbuffer str= new stringbuffer( "" ); file file= new file(file_in); try { filereader fr= new filereader(file); int ch = 0 ; while ((ch = fr.read())!=- 1 ) { system.out.print(( char )ch+ " " ); } fr.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); system.out.println( "file reader出錯" ); } return str.tostring(); } |
方式三
/按字節讀取字符串/
/* 個人感覺最好的方式,(一次讀完)讀字節就讀字節吧,讀完轉碼一次不就好了*/
private static string readstring3()
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
string str= "" ; file file= new file(file_in); 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, "gb2312" ); } catch (ioexception e) { // todo auto-generated catch block return null ; e.printstacktrace(); } return str; |
}
方式四
/inputstreamreader+bufferedreader讀取字符串 , inputstreamreader類是從字節流到字符流的橋梁/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
/* 按行讀對于要處理的格式化數據是一種讀取的好方式 */ private static string readstring4() { int len= 0 ; stringbuffer str= new stringbuffer( "" ); file file= new file(file_in); try { fileinputstream is= new fileinputstream(file); inputstreamreader isr= new inputstreamreader(is); bufferedreader in= new bufferedreader(isr); string line= null ; while ( (line=in.readline())!= null ) { if (len != 0 ) // 處理換行符的問題 { str.append( "\r\n" +line); } else { str.append(line); } len++; } in.close(); is.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } return str.tostring(); } |
路要一步一步走,記住自己走過的路,不再犯同樣的錯誤,才是真正的成長!歡迎指點、交流。
以上這篇java中讀取文件轉換為字符串的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/stimgo/article/details/52856570