[英]Is there a way to display all the contents in a file as it is using a single string object
I am writing an android app for which I want to write a function that parses a text file collecting all the lines and putting it into single String object and display the contents as it was in the file. 我正在编写一个Android应用程序,我想为其编写一个函数,该函数分析收集所有行的文本文件并将其放入单个String对象中,并按文件中的内容显示内容。 The display should be along with all the 'new line' characters which is present in the text file.
显示内容应与文本文件中所有“换行”字符一起显示。 How can I do this?
我怎样才能做到这一点?
Also like an end of file, Is there a way to use another identifier within a file so that I can have multiple portions within the same file ? 就像文件结尾一样,是否可以在文件中使用另一个标识符,以便在同一个文件中包含多个部分?
Thanks in advance 提前致谢
Below is a sample to read data from a text file into a String object. 下面是将文本文件中的数据读取到String对象中的示例。 In this example, the text file is part of assets.
在此示例中,文本文件是资产的一部分。 You can get an InputStream from opening files from sdcard also :
您还可以通过从sdcard打开文件来获取InputStream:
public class AssetsTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
setContentView(textView);
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("texts/myawesometext.txt");
String text = loadTextFile(inputStream);
textView.setText(text);
} catch (IOException e) {
textView.setText("Couldn't load file");
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
textView.setText("Couldn't close file");
}
}
}
public String loadTextFile(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int len = 0;
while ((len = inputStream.read(bytes)) > 0)
byteStream.write(bytes, 0, len);
return new String(byteStream.toByteArray(), "UTF8");
}
You can store what you parse from the text file in a single String that's no problem. 您可以将文本文件中解析的内容存储在单个String中,这没有问题。
You can also use different Strings for each line of text but it'll be pretty much resource consuming and unnecessary. 您还可以为每行文本使用不同的字符串,但是这将浪费大量资源,并且不必要。
To put it short yes you can use one String for your question. 简而言之,可以为您的问题使用一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.