从文本文件中读取并存储在字符串中 [英] Reading from a text file and storing in a String
本文介绍了从文本文件中读取并存储在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从文本文件中读取数据并存储在字符串变量中?
How can we read data from a text file and store in a String variable?
是否可以在方法中传递文件名,它会返回字符串,即文件中的文本.
is it possible to pass the filename in a method and it would return the String which is the text from the file.
我必须导入哪些实用程序?陈述清单会很棒.
What kind of utilities do I have to import? A list of statements will be great.
推荐答案
这些是必要的导入:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
这是一种允许您通过将文件名作为参数传递给文件来读取文件的方法,如下所示:readFile("yourFile.txt");
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("
");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
这篇关于从文本文件中读取并存储在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文