Wednesday, February 20, 2019

Java read file txt

We want to read a txt file, first, use notepad to create a txt file, save it with UTF-8 Encoding.

Create a folder name raw, copy file txt in to it.

In class, we need a textView to show, name it tv.
Copy this lines below findViewById.
InputStream in = this.getResources().openRawResource(R.raw.tho);
     try
      {
     byte[] buffer = new byte[in.available()];
     while (in.read(buffer) != -1);
     String jsontext = new String(buffer);

       tv.setText(jsontext);         
          
     }
   catch (IOException e)
     {
             //return null;
}
Press Ctrl+Shift+O to import libraries.

Run to see the result.

Now we want to read file to lines, add them in to an array.
Declare an arraylist.
ArrayList<String> ar = new ArrayList<String>();
Replace the codes above by this lines.
String line = "";
     try {
InputStream  In = this.getResources().openRawResource(R.raw.tho);
               InputStreamReader inputReader = new InputStreamReader(In);
               BufferedReader BR = new BufferedReader(inputReader);
     while ((line = BR.readLine()) != null) {
          ar.add(line);
     }
BR.close();

} catch (IOException e) {
e.printStackTrace();
}
tv.setText(ar.get(2));
Here we read file to an array and set the third line to textView.


No comments:

Post a Comment