bl双性强迫侵犯h_国产在线观看人成激情视频_蜜芽188_被诱拐的少孩全彩啪啪漫画

使用Java怎么將讀取的文件轉換為字符串

這篇文章給大家介紹使用Java怎么將讀取的文件轉換為字符串,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

成都創新互聯公司基于分布式IDC數據中心構建的平臺為眾多戶提供四川主機托管 四川大帶寬租用 成都機柜租用 成都服務器租用。

方式一

/**

以字節為單位讀取文件,常用于讀二進制文件,如圖片、聲音、影像等文件。

當然也是可以讀字符串的。

*/

/* 貌似是說網絡環境中比較復雜,每次傳過來的字符是定長的,用這種方式?*/
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();
}

關于使用Java怎么將讀取的文件轉換為字符串就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

文章標題:使用Java怎么將讀取的文件轉換為字符串
轉載來于:http://vcdvsql.cn/article2/gghooc.html

成都網站建設公司_創新互聯,為您提供關鍵詞優化建站公司微信小程序網站內鏈網站維護網站改版

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

營銷型網站建設