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 ?
Related
I am trying to read in a file using the fstream. I am writing in C++11, but interfacing it with Java via JNI in Android Studio. It doesn't open the file for some reason. I am using a relative file path and I don't understand why it can't open the file. The file is named proverbs.txt. There aren't any discrepancies within the name like proverbs.txt.txt or anything like that.
Here's the code:
void storeProverbs() {
string path = "/Users/tenealaspencer/Desktop/proverbs.txt";
std::ifstream provInput(path.c_str(), std::ios::in);
//provInput.open("/Users/tenealaspencer/Desktop/proverbs.txt");
// opens the proverbs text file
equivInput.open("/Users/tenealaspencer/AndroidStudioProjects/example/app/src/main/cpp/stored.txt"); // opens the stored (English) proverbs text file
if (!provInput.is_open()) {
cout << "error ";
}
while (!provInput.eof()) // while not at the end of the proverbs file
{
getline(provInput, phrase); // read proverbs in line by line
getline(equivInput, storedProv); // read english proverbs in line by line
Never mind I just imported the file via Java using the following code:
try {
InputStream is = getAssets().open("stopwords.txt");
String line1;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while((line1 = reader.readLine()) != null) //
{
try {
byte[] utf8Bytes = line1.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
storeStopWords(line1);
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
InputStream is = getAssets().open("proverbs.txt");
InputStream iz = getAssets().open("stored.txt");
String line;
String line2; //= new String ("");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader reader2 = new BufferedReader(new InputStreamReader(iz));
while((line = reader.readLine()) != null && (line2 = reader2.readLine()) != null ) //
{
try {
byte[] utf8Bytes = line.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
storeProverbs(line,line2);
}
}
catch (IOException e) {
e.printStackTrace();
}
I read somewhere that JNA doesn't support the fstream library or something like that. In any case it works.
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();
}
I have a file in my devise called test.csv. when i click on that file is opened through my app.how to set default open with(dialog) option to my app in android?
above is the sample dailog.how to add my app to the dialog list?
I think you may want to read the csv file. you could get the csv file path. So see the following.
public static void readCSV(File file) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file));// your csv file
reader = new BufferedReader(isr);
String line = null; // every time read one line
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The stringBuilder.toString() is your csv file's content. Sorry for my English.
I'm participating in an online Android course and have (so far) gotten no response on their forum to this issue. I'm using Android Studio on Windows 8.1.
I have the following function to read a file and load an adapter:
private void loadItems() {
BufferedReader reader = null;
try {
FileInputStream fis = openFileInput(FILE_NAME);
reader = new BufferedReader(new InputStreamReader(fis));
String title = null;
String priority = null;
String status = null;
Date date = null;
while (null != (title = reader.readLine())) {
priority = reader.readLine();
status = reader.readLine();
date = ToDoItem.FORMAT.parse(reader.readLine());
mAdapter.add(new ToDoItem(title, Priority.valueOf(priority),
Status.valueOf(status), date));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My questions are:
I don't find the file named by the constant FILE_NAME anywhere on my hard drive. If the file doesn't exist shouldn't openFileInput() throw FileNotFoundException?
Why does InputStreamReader not throw an error?
Via the debugger, I've watched as The logic guarding entry into the WHILE construct happily allows a null value in the title variable to enter the loop. Am I missing something here?
Thanks in advance for any light anyone can shed!!
Markb
I want to save my app logcat events in a text file on sd card.
my alarming app work properly in my and my friends devices, but other have error on my app.
for example they say alarms in app are in wrong time, but i dont see this error in my and my friends devices.
Because of this issue and other issues, i want save all events logcat related my app, atomatically. so they send log file to me to solve issues.
how can i do this?
thanks
sorry for my bad english
You can get logcat via the following:
static final int BUFFER_SIZE = 1024;
public String getLogCat() {
String[] logcatArgs = new String[] {"logcat", "-v", "time"};
Process logcatProc = null;
try {
logcatProc = Runtime.getRuntime().exec(logcatArgs);
}
catch (IOException e) {
return null;
}
BufferedReader reader = null;
String response = null;
try {
String separator = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), BUFFER_SIZE);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(separator);
}
response = sb.toString();
}
catch (IOException e) {
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {}
}
}
return response;
}
You can then save this String to the sdcard.
You can get logcat via the following:
static final int BUFFER_SIZE = 1024;
public String getLogCat() {
String[] logcatArgs = new String[] {"logcat", "-v", "time"};
Process logcatProc = null;
try {
logcatProc = Runtime.getRuntime().exec(logcatArgs);
}
catch (IOException e) {
return null;
}
BufferedReader reader = null;
String response = null;
try {
String separator = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), BUFFER_SIZE);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(separator);
}
response = sb.toString();
}
catch (IOException e) {
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {}
}
}
return response;
}
You can then save this String to the sdcard.
This answer from "Dororo" didn't work for me since it always got stuck in the while due to to many lines, but i have no idea how to fix that.
the logcat will block for reading new logs unless you specify the '-d' arg.
try
String[] logcatArgs = new String[] {"logcat", "-d", "-v", "time"};
This type of functionality is already implemented by the ACRA Android library. The library detects crashes, and send the crash information to either a Google Docs spreadsheet, or your own destination.
Execute within a thread to avoid ANRs