日期:2014-05-20 浏览次数:20829 次
public String fileToString(String fileName) { StringBuilder fileContent = new StringBuilder(); File file = new File(fileName); BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String string; while ((string = br.readLine()) != null) { fileContent.append(string); fileContent.append("\n"); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (br != null) try { br.close(); } catch (IOException e) { throw new RuntimeException(e); } } return fileContent.toString(); }
------解决方案--------------------
这个帖子和你要做的是一回事如何用java 读取一个txt 文件内的内容并把它赋值与String 里?
------解决方案--------------------
Java code
public String fileToString(String fileName) {
StringBuilder fileContent = new StringBuilder();
File file = new File(fileName);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String string;
while ((string = br.readLine()) != null) {
fileContent.append(string);
fileContent.append("\n");
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return fileContent.toString();
}
对的
------解决方案--------------------
按行读取文件内容,然后做你想做的事。
楼主想把所有内容读出来然后放到一个字符串中,2楼的代码能说明问题了,
然后对于你的代码:
fileContent += br.readLine();