使用Java怎么将读取的文件转换为字符串

发布时间:2021-01-21 17:09:30 作者:Leah
来源:亿速云 阅读:453

这篇文章给大家介绍使用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();
}

关于使用Java怎么将读取的文件转换为字符串就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 使用Java怎么将Exception信息转换为String字符串
  2. 使用java怎么将生成的xml转换为字符串

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 字符串

上一篇:如何在Android中对字符串进行压缩

下一篇:利用Java怎么将字符串转换为可执行代码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》