简体   繁体   中英

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. 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. In this example, the text file is part of assets. You can get an InputStream from opening files from sdcard also :

    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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM