如何用Java读取一个txt文件,并将文件内容保存到String类型的变量中?求Java代码!

 我来答
flyingFish211
推荐于2018-03-03 · TA获得超过2.1万个赞
知道大有可为答主
回答量:1.5万
采纳率:50%
帮助的人:1.1亿
展开全部
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

public static void main(String[] args) throws IOException {

String fileContent = readFileContent("");

System.out.println(fileContent);
}

//参数string为你的文件名
private static String readFileContent(String fileName) throws IOException {

File file = new File(fileName);

BufferedReader bf = new BufferedReader(new FileReader(file));

String content = "";
StringBuilder sb = new StringBuilder();

while(content != null){
content = bf.readLine();

if(content == null){
break;
}

sb.append(content.trim());
}

bf.close();
return sb.toString();
}
}
flyingFish211
2018-01-05 · TA获得超过2.1万个赞
知道大有可为答主
回答量:1.5万
采纳率:50%
帮助的人:1.1亿
展开全部
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

public static void main(String[] args) throws IOException {

String fileContent = readFileContent("");

System.out.println(fileContent);
}

//参数string为你的文件名
private static String readFileContent(String fileName) throws IOException {

File file = new File(fileName);

BufferedReader bf = new BufferedReader(new FileReader(file));

String content = "";
StringBuilder sb = new StringBuilder();

while(content != null){
content = bf.readLine();

if(content == null){
break;
}

sb.append(content.trim());
}

bf.close();
return sb.toString();
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
嘚瑟的小蹦蹦
2011-02-26 · TA获得超过108个赞
知道答主
回答量:105
采纳率:50%
帮助的人:35.2万
展开全部
Reader reader = null;
BufferedReader br = null;
try {

reader = new FileReader("txt文件地址");
br = new BufferedReader(reader);
StringBuffer sb = new StringBuffer();
String data = null;
while ((data = br.readLine()) != null) {
sb.appand(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式