導航:首頁 > 編程語言 > javastring效率

javastring效率

發布時間:2023-08-20 02:57:59

Ⅰ JAVA中幾種讀取文件字元串的效率哪個比較高

方式一

/**
* 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
* 當然也是可以讀字元串的。
*/
/* 貌似是說網路環境中比較復雜,每次傳過來的字元是定長的,用這種方式?*/
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吧
// 每次讀一個是不是效率有點低了?
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()
{
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類是從位元組流到字元流的橋梁*/
/* 按行讀對於要處理的格式化數據是一種讀取的好方式 */
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();
}

閱讀全文

與javastring效率相關的資料

熱點內容
php文件系統源碼 瀏覽:708
易信java 瀏覽:481
北侖二級壓縮螺桿機 瀏覽:44
加密路線免費入口 瀏覽:739
計算器程序員是幹嘛的 瀏覽:362
數控編程里fo是啥鍵 瀏覽:655
javacdataxml 瀏覽:943
本機tcp伺服器地址 瀏覽:426
切換pdf 瀏覽:92
iturns下載的app在哪裡 瀏覽:641
雲起書院App在哪裡 瀏覽:615
怎麼對hex文件進行加密 瀏覽:285
pdf少年時 瀏覽:953
兩個同名文件夾同步 瀏覽:630
拍照文件夾哪個好用 瀏覽:91
文件夾和書包 瀏覽:511
解壓歸檔拿登記證 瀏覽:225
去體驗解壓房 瀏覽:613
單片機一鍵中斷響應 瀏覽:647
唐浩明pdf 瀏覽:845