Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a textfile using InputStream

Tags:

How can I read a text file like in android app:

"1.something written 2.in this file 3.is to be read by 4.the InputStream ..." 

so I can be returned a string like:

"something written\nin this file\nis to be read by\nthe InputStream" 

what I thought of is(Pseudocode):

make an inputstream is = getAssest().open("textfile.txt");  //in try and catch for loop{ string = is.read() and if it equals "." (i.e. from 1., 2., 3. etc) add "/n" ... } 
like image 605
RE60K Avatar asked Feb 12 '13 04:02

RE60K


People also ask

How do I read a file as InputStream?

make an inputstream is = getAssest(). open("textfile. txt"); //in try and catch for loop{ string = is. read() and if it equals "." (i.e. from 1., 2., 3.

How do you load a file in Java?

Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.

How do I get ByteArrayInputStream from a file?

Use the FileUtils#readFileToByteArray(File) from Apache Commons IO, and then create the ByteArrayInputStream using the ByteArrayInputStream(byte[]) constructor. Show activity on this post. create a ByteArrayInputStream around the file content, which is now in memory.


1 Answers

try this

import android.app.Activity; import android.os.Bundle; import android.widget.Toast; import java.io.*;  public class FileDemo1 extends Activity {      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         try {             playWithRawFiles();         } catch (IOException e) {             Toast.makeText(getApplicationContext(), "Problems: " + e.getMessage(), 1).show();         }     }      public void playWithRawFiles() throws IOException {               String str = "";         StringBuffer buf = new StringBuffer();                     InputStream is = this.getResources().openRawResource(R.drawable.my_base_data);         try {             BufferedReader reader = new BufferedReader(new InputStreamReader(is));             if (is != null) {                                             while ((str = reader.readLine()) != null) {                         buf.append(str + "\n" );                 }                             }         } finally {             try { is.close(); } catch (Throwable ignore) {}         }         Toast.makeText(getBaseContext(), buf.toString(), Toast.LENGTH_LONG).show();     } } 
like image 90
Yogesh Tatwal Avatar answered Oct 20 '22 20:10

Yogesh Tatwal