Importing Text File in Android Application? - android

I've been getting the following error when I attempt to run an android application that inputs data from a text file.
"java.io.fileNotFoundException: /File.txt: open failed:ENOENT (No such file or directory)"
The file in question is in the Eclipse project folder.
I also tried putting it in the assets folder as well as several others.
Here is the code in question:
File file = new File("File.txt");
TestOutput = new ArrayList<String>();
String x = "";
try
{
Scanner scanner = new Scanner(file);
while (sc.hasNextLine())
{
x = sc.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
So far I have attempted to use a wrapper class to no avail, the code of which is below:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileGet
{
ArrayList<String> TestOutput = new ArrayList<String>();
public FileGet() {
}
public ArrayList<String> getFile() {
File file = new File("TestOutput.txt");
TestOutput = new ArrayList<String>();
try
{
Scanner scanner = new Scanner(file);
String x = "";
while (scanner.hasNextLine())
{
x = scanner.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return TestOutput;
}
}
That code works fine outside of the android application. Any advice/responses would be greatly appreciated.

Try this, the string named "line" is the string where all the TextFile is read.
Put the .txt file under /resources/raw folder.
InputStream is = getResources().openRawResource(R.raw.name_of_file);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line = null;
try {
while ((line = r.readLine()) != null)
total.append(line);
} catch (IOException e) {
e.printStackTrace();
}
line = total.toString();

Related

Edit csv file with Excel without reformatting in android

I'm trying to make a simple android app that basically imports a csv and inserts it to customised Array list. So far, I was able to read a csv file when I had not updated CSV file content.I found when I update CSV file with excel it change the formate of csv file.
Here is my code for reading csv file:
selectedFile = new File(data.getStringExtra(FilePicker.EXTRA_FILE_PATH));
ArrayList<Expense> objList= new ArrayList<>();
String file=selectedFile.getPath();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(selectedFile.getPath()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(fileInputStream, Charset.forName("UTF-8")));
String line = "";
StringTokenizer st = null;
try {
while ((line = reader.readLine()) != null) {
st = new StringTokenizer(line, ",");
ExpenseShare obj= new ExpenseShare ();
//your attributes
obj.setAmount(st.nextToken());
obj.setName(st.nextToken());
obj.setDate(st.nextToken());
obj.setTime(st.nextToken());
objList.add(obj);
Log.e("latasingh"," "+obj.getName()+" "+(obj.getAmount())+" "+obj.getDate()+" "+ obj.getTime()); //I understood this problem by seeing log data.
}
} catch (IOException e) {
e.printStackTrace();
}
How can I resolved this problem.
Thank You !!

Read data of type double from a text file in Android

I want to read data of type double saved in a .txt file from a previously specified folder. I've implemented the following code to read data then put them in an array of type double named savg1. when I run my application , it going to crash and the application stop. I tried to debug the application step by step and found that crash happens when the code reaches to savg1[i] = Double.parseDouble(str).
public void filereader()
{
InputStream is=this.getResources().openRawResource(R.raw.nums);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=null;
int i=0;
try
{
if (is !=null)
{
str=br.readLine();
while (str != null) {
savg1[i] = Double.parseDouble(str);
i++;
str=br.readLine();
}
is.close();
br.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
I am a newbie in Android developing so excuse me about my elementary question. Can anybody guide me how I can solve this problem?
Use following code to read data from your file. Note that in this method each number should be in a separate line:
double svg1[] = new double[10];
try {
InputStream is = getResources().openRawResource(R.raw.data);
DataInputStream dis = new DataInputStream(is);
while (dis.available() > 0) {
String test = dis.readLine();
double a = Double.parseDouble(test);
}
}catch (Exception e){
e.printStackTrace();
}
You can use file scanner for reading double type data saved in a text file as bellow:
public void fileReader(){
Scanner scan;
File file = new File("resources\\scannertester\\data.txt");
int idx = 0;
try {
scan = new Scanner(file);
while(scan.hasNextDouble())
savg1[idx++] = scan.nextDouble();
} catch (FileNotFoundException error) {
error.printStackTrace();
}
scan.close();
}

Need help to read text from text file to ArrayList<String> (Android)

i am working on an image gallery app in which i am loading images from URL so i have saved some image URLs in a text file and i am trying to read URLs from text file to ArrayList<String> but i am not able to load images in my app.
i tried this: but not works images are not loading
package com.nostra13.example.universalimageloader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class Constants {
public static List<String> LIST = new ArrayList<String>();
public void parseFile() {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("link.txt"));
while ((sCurrentLine = br.readLine()) != null) {
LIST.add(sCurrentLine);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static final String[] IMAGES = LIST.toArray(new String[LIST.size()]);
private Constants() {
}
public static class Config {
public static final boolean DEVELOPER_MODE = false;
}
public static class Extra {
public static final String IMAGES = "com.nostra13.example.universalimageloader.IMAGES";
public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";
}
}
but if i add URLs manually like this: it works.
public static final String[] IMAGES = new String[] {
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
};
but i want to add text from text file (sdcard/file.txt) instead of manually adding.
Well, did you try and use Log.d() to post the lines of text that is being read from the file?
My best guess is that it's not reading the text file correctly, or perhaps formatting it wrongly (missing spaces perhaps, so it thinks its 1 big string?)
Try with this code:
public void parseFile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"link.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
LIST.add(sCurrentLine);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
The call to Environment.getExternalStorageDirectory() will return the path of SD card, and the path of declared variable file is relative to the root of SD card. If the file on a folder, you should declare:
File file = new File(sdcard,"data/com.myapplication.example/images/link.txt");

Can not write more than 1 line into file

I am trying to write to a text file a list of names. It is written one line at a time and I have a class for Writing to File and Reading from it.
Here is the class:
package com.example.mobiledayoff;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
public class userListIO {
Context fileContext;
public userListIO(Context fileContext){
this.fileContext=fileContext;
}
public void writeItems(String fileName, String name){
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer =
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
writer.write(name + ls);
} catch (Exception e){
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<CharSequence> readItems(String filename){
ArrayList<CharSequence> list = new ArrayList<CharSequence> ();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fileContext.getApplicationContext().openFileInput(filename)));
String line;
while((line = br.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}
I use this class to write a line from user input (EditText) to the file. And then I read from file and Display contents of the file in another EditText. Here is how I do it:
public void addUser(View view){
EditText text = new EditText(this);
text = (EditText)findViewById(R.id.add_user_text);
String name = text.getText().toString();
String filename = "userList.txt";
userListIO messenger = new userListIO(this);
messenger.writeItems(filename, name);
text.setText("");
ArrayList<CharSequence> list = messenger.readItems(filename);
EditText editText = (EditText) findViewById(R.id.debug_text);
String info = "";
int count = 0;
for (CharSequence item: list){
info += item.toString();
count++;
}
info += "; there are " + count + " lines";
editText.setText(info);
}
My main problem is that it seems that file gets overwritten each time I write into it and so I always have 1 line. Do you guys know how to fix this? By fix I mean: How to append to the file if it already exists or create one if it doesn't exist.
Also I found out that after I close and reopen an app, the file does not exist. How to create and save a file, so that after closing and reopening I could still use the data stored there?
p.s. Read/Write was taken from here:
The best way to store user input data for later work
Change
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
to
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE | Context.MODE_APPEND)));
This will combine the MODE_PRIVATE flag aswell as the MODE_APPEND flag.
P.S. You should get away from opening and closing a stream everytime you write a line. This produces a lot of overhead and rather should you try to keep the stream opened until all your data has been processed.

CSV file cannot be accessed via BufferedReader in Android

I am trying to read a CSV file using BufferedReader in android. My program works perfectly fine in Java but when I try read those data from Android following error I get.
01-31 17:09:58.466: W/System.err(15912): java.io.FileNotFoundException:
/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv: open failed: ENOENT (No
such file or directory)
Following code I am using here.
public double getLongitudes() {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
double longitudes = 0;
try {
br = new BufferedReader(
new FileReader(
"/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv"));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
longitudes = Double.parseDouble(country[5]);
Log.d("worked", "worked");
// System.out.println("Latitude " + longitudes);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return (longitudes);
}}
Any idea why its happening ??
The path /Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv is invalid. This looks like the path to a file on your computer rather than your Android device. You need to push the file to your device or your emulated device and access it from there. Even the Android emulator will not read files directly from your computer's filesystem.
Proper way to store your CSV in Android is:
("/sdcard/Android/data/filename.csv");
The .csv file needs to be in your project resources. You can copy the file into assets folder and read it this way
AssetInputStream asset_stream = (AssetInputStream)getAssets().open("input.csv");
InputStreamReader reader = new InputStreamReader(asset_stream);
BufferedReader br = new BufferedReader(reader);
This is one method that has worked for me before.
Another method would be to put the file into res/raw folder and access it
InputStream file = getResources().openRawResource(R.raw.inputfile);
You can also refer to https://stackoverflow.com/a/3851429/3092829
Hope this helps!
So i have solved my problem.
public class ReadCSV {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
String[] country;
AssetInputStream asset_stream = null;
public String[] getLatitude() {
try {
asset_stream = (AssetInputStream) MainActivity.getContext()
.getAssets().open("Input.csv");
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader reader = new InputStreamReader(asset_stream);
Log.d("logg", "log" + reader);
br = new BufferedReader(reader);
Log.d("logg", "log" + br);
try {
while ((line = br.readLine()) != null) {
country = line.split(cvsSplitBy);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return country;
}
As you can see I am trying to get my latitude by returning it through country. But when I trying get it from another fragment class through this,
String[] lat;
lat = csv.getLatitude();
Log.d("", "" + lat);
Why I don't get latitude back ?

Categories

Resources