java读取文件文件内容到字符串_java读取文件内容为string字符串的方法

java读取文件内容为string字符串的方法

发布于 2020-6-11|

复制链接

分享一篇关于java读取文件内容为string字符串的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小妖过来看看吧

直接就把项目中的方法贴出来吧

```java

/**

* 读出城市列表文件

*/

private String readCityFile() {

File file02 = new File(path_xinfu, "/cityList.json");

FileInputStream is = null;

StringBuilder stringBuilder = null;

try {

if (file02.length() != 0) {

/**

* 文件有内容才去读文件

*/

is = new FileInputStream(file02);

InputStreamReader streamReader = new InputStreamReader(is);

BufferedReader reader = new BufferedReader(streamReader);

String line;

stringBuilder = new StringBuilder();

while ((line = reader.readLine()) != null) {

// stringBuilder.append(line);

stringBuilder.append(line);

}

reader.close();

is.close();

} else {

mLoadingLayout.setStatus(LoadingLayout.Empty);

}

} catch (Exception e) {

e.printStackTrace();

}

return String.valueOf(stringBuilder);

}

```

public static String loadAFileToStringDE1(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new BufferedInputStream( new FileInputStream(f) ); long contentLength = f.length(); ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : 1024); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); ret = outstream.toString(); //byte[] ba = outstream.toByteArray(); //ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法1用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE2(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new FileInputStream(f) ; long contentLength = f.length(); byte[] ba = new byte[(int)contentLength]; is.read(ba); ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法2用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE3(File f) throws IOException { long beginTime = System.currentTimeMillis(); BufferedReader br = null; String ret = null; try { br = new BufferedReader(new FileReader(f)); String line = null; StringBuffer sb = new StringBuffer((int)f.length()); while( (line = br.readLine() ) != null ) { sb.append(line).append(LINE_BREAK); } ret = sb.toString(); } finally { if(br!=null) {try{br.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法3用时"+ (endTime-beginTime) + "ms"); return ret; } 3个方法读取一个大于50M的文件,当不设置jvm参数时都OutofMemery,当设置-Xmx128M时。只有方法3 可以通过,设置到-Xmx256M时也只有方法3可以通过,干脆设置512M,都可以了,运行时间如果正常的话一般都在4~5S
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页