How can I read a text file in Android? - java

I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the application folder. Where should I put this text file (mani.txt) in order to read it correctly?
try
{
InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt");
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line,line1 = "";
try
{
while ((line = buffreader.readLine()) != null)
line1+=line;
}catch (Exception e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
String error="";
error=e.getMessage();
}

Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file

If you want to read file from sd card. Then following code might be helpful for you.
StringBuilder text = new StringBuilder();
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : "+text+" : end");
text.append('\n');
} }
catch (IOException e) {
e.printStackTrace();
}
finally{
br.close();
}
TextView tv = (TextView)findViewById(R.id.amount);
tv.setText(text.toString()); ////Set the text to text view.
}
}
If you wan to read file from asset folder then
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:
InputStream is = getResources().openRawResource(R.raw.test);
Good example of reading text file from res/raw folder

Put your text file in Asset Folder...& read file form that folder...
see below reference links...
http://www.technotalkative.com/android-read-file-from-assets/
http://sree.cc/google/reading-text-file-from-assets-folder-in-android
Reading a simple text file
hope it will help...

Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}

First you store your text file in to raw folder.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}

Shortest form for small text files (in Kotlin):
val reader = FileReader(path)
val txt = reader.readText()
reader.close()

Try this
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}

Related

Java getting id from csv file to combo box

I am have a program were there are two forms one for the consultant and for the customer. On the first form the user will enter the consultant details and his ID will be saved in a csv file and this works fine.
Consultant cons_save = new Consultant();
cons_save.setPersonfirstname(this.jTextField1.getText());
cons_save.setPersonlastname(this.jTextField2.getText());
cons_save.setPersonID(this.jTextField4.getText());
this.jTextField1.setText("");
this.jTextField2.setText("");
this.jTextField3.setText("");
cons_save.ConsultantID = cons_save.PersonID;
cons_save.setConsultantID(this.jTextField4.getText());
this.jTextField4.setText("");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter("E:\\ryan_assignment_sit2\\ConsID\\consID.csv", true));
writer.append(cons_save.ConsultantID);
writer.append(",");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
cons_save.savecons();
After the id is saved the Id is called out from the csv to an array and this works fine as well.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
Vector<String> vectorData = new Vector<String>(ConsIDList);
DefaultComboBoxModel<String> comboBoxModel = new DefaultComboBoxModel<>(vectorData);
this.jComboBox1.setModel(comboBoxModel);
}
}
The array is working fine but the combo box is not getting populated with the arraylist.

Make text viewer read files faster in android

I have a simple text viewer class that opens text file and reads the strings. But the problem is, when the file is large >0.5Mb, opening takes quite a while. Is there a way to load small part first and then load all others or any other way to make this process faster ? Here is my code:
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
TextView txt = (TextView)findViewById(R.id.textView);
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null) {
try {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(buf.toString());
}
}

read from csv, delete line based on first portion

In my app I am displaying the first portion of each line of the CSV in a JList, and when it is selected and a button is pressed (delete) I want it to remove that line from the file based on the first entry. I am trying the method where you have a temp file then write to it then rename it at the end but that isnt working out for some reason. Any ideas?
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Delete service
String selected = (String) jList1.getSelectedValue();
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = new File("/users/aak7133/desktop/temp.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(passwords));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
//String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line);
}
boolean successful = temp.renameTo(passwords);
} catch (Exception e) {
}
updateList();
clearFields();
}
The problem is actually caused by the open reader and writer. This should work:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String selected = (String) jList1.getSelectedValue();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = File.createTempFile("temp", ".txt", new File("/users/aak7133/desktop/"));
reader = new BufferedReader(new FileReader(passwords));
writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
// String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line + "\n");
}
if (passwords.canWrite()) {
try {
reader.close();
reader = null;
} catch (IOException ignore) {}
try {
writer.close();
writer = null;
} catch (IOException ignore) {}
String path = passwords.getAbsolutePath();
passwords.delete();
boolean successful = temp.renameTo(new File(path));
System.out.println(successful);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {}
}
}
updateList();
clearFields();
}
I figured out I needed to put passwords.delete() before temp.renameTo(passwords). This fixed the issue right away.

Reading From a File saved in the /res or /asset folder? Android

I am trying to read a text file and save each line of text into an ArrayList. I have tried various methods, including FileInputStream and BufferedReader. Here is the code that currently gets me the closest to what I am trying to do
try {
InputStream is = getResources().openRawResource(R.File.txt);
BufferedReader bufferedReader = new BufferedReader(new FileReader("File.txt"));
String line;
while((line = bufferedReader.readLine()) != null)
{
allText.add(line);
}
bufferedReader.close();
}
catch(IOException e)
{
}
allText is an ArrayList previously instantiated. Right now the file is saved in /res and I get an "invalid resource directory warning". I would like to know where to save the file properly and how to read from it.
The line should be
InputStream is = getResources().openRawResource(R.File.txt);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
You have made an InputStream for resource file and use BufferedReader to read from the stream created.
Reading from /assets folder use getAssets() method
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("File.txt"), "UTF-8"));
String myData = reader.readLine();
while (myData != null) {
myData = reader.readLine();
}
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
Reading file from /res/raw folder
InputStream fileInputStream = getResources().openRawResource(R.raw.File);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = fileInputStream .read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
fileInputStream .close();
} catch (IOException e) {
}
return outputStream.toString();
}

Saving to Android Internal Storage

At the moment i'm trying to save a response to the internal storage in the phone. Everything works fine up until i try and retrieve the data again. When i log out the retrieved data it only logs out one small section of the response and the rest isn't there. Ive tried deleting the file and calling it again just incase it was using an old one.
Saving Code
try {
String response = apiResponse.getRawResponse();
Log.e("Response", response);
FileOutputStream userInfo = openFileOutput("personal_profile", MODE_PRIVATE);
userInfo.write(response.getBytes());
userInfo.close();
} catch (Exception e) {
e.printStackTrace();
Retrieving Code
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Saved File", response);
Any kind of suggestions would be great!
REASON
The problem was that the line variable is assigned again in every iteration
Try this:
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
CHANGE LAST LINE
Log.e("Saved File", sb.toString());
Have you got this in your AndroidManifest.xml file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, this link has everything you need to know about reading and writing files:
http://www.anddev.org/working_with_files-t115.html
Code::
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Saved File", sb.toString());

Categories

Resources