问题:
Android开发中难免会使用到Java基础的知识进行编程,今天开发中需要将文件读取出来,然后转换为字符串,由于长时间不写io操作,导致google了半天,在这里作为保存备份,以便下次方便查找。
解决:
分段读取
private String inputStreamToString(final String fileName, InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
byte[] buffer = new byte[512];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
String string = new String(buffer, 0, length, "UTF-8");
stringBuilder.append(string);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
逐行读取
private String streamToString(final String fileName, InputStream inputStream) {
StringBuilder builder = new StringBuilder();
InputStreamReader streamReader = null;
BufferedReader bufferedReader = null;
try {
streamReader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(streamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
streamReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
结论
由于Java IO操作部分类比较多,用起来相对来说也不好记忆,还是需要多多使用、总结、记忆。
网友评论