導航:首頁 > 編程語言 > 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效率相關的資料

熱點內容
相片如何用電解壓 瀏覽:905
碩士程序員去學校當老師 瀏覽:120
pythonstr提取到字典 瀏覽:818
程序員那麼可愛有人看上陸漓了 瀏覽:876
php正則提取圖片 瀏覽:103
pythonlinuxdjango 瀏覽:562
php中文返回亂碼 瀏覽:89
宿舍裝的電信怎麼加密 瀏覽:745
為什麼壓縮文件解壓後變少了 瀏覽:426
現在安卓充電器普遍是什麼型號 瀏覽:714
9日均線36均線主圖指標源碼 瀏覽:349
程序員阿里文化完整版 瀏覽:98
早間新聞在哪個app上面可以看 瀏覽:954
工作啦app注冊的信息怎麼刪去 瀏覽:378
滾動轉子式製冷壓縮機 瀏覽:873
美國編程用什麼軟體 瀏覽:571
圖片加密防盜用 瀏覽:616
dbscan演算法python源碼 瀏覽:849
固態硬碟文件夾刪不掉 瀏覽:717
陽泉工會app怎麼培訓報名 瀏覽:669