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 !!
Related
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 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 ?
I've searched for a couple days, and all I find is using bufferedReader to read from a file on internal storage. Is it not possible to use InputStream to read from a file on internal storage?
private void dailyInput()
{
InputStream in;
in = this.getAsset().open("file.txt");
Scanner input = new Scanner(new InputStreamReader(in));
in.close();
}
I use this now with input.next() to search my file for the data that I need. It all works fine, but I would like to save new files to internal storage and read from them without changing everything to bufferedReader. Is this possible or do I need to bite the bullet and change everything? FYI I don't need to write, only read.
To write a file.
String FILENAME = "file.txt";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to read
void OpenFileDialog(String file) {
//Read file in Internal Storage
FileInputStream fis;
String content = "";
try {
fis = openFileInput(file);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
}
content += new String(input);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
content will Contain your File Data.
You may try following code when you face a condition to read a file from a subfolder in internal storage. Sometimes you may get problems with openFileInput whey you trying to passing context.
here is the function.
public String getDataFromFile(File file){
StringBuilder data= new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String singleLine;
while ((singleLine= br.readLine()) != null) {
data.append(singleLine);
data.append('\n');
}
br.close();
return data.toString();
}
catch (IOException e) {
return ""+e;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
android reading from a text file
So I need to load text, but I don't know how :( To save text I'm doing this
File logFile = new File("sdcard/data/agenda.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(editText1.getText());
buf.newLine();
buf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
So, how to load it back by button tap?
To read content of file, for example *.txt - do this...
private String GetPhoneAddress() {
File file = new File(Environment.getExternalStorageDirectory() + "/reklama/tck.txt");
if (!file.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
Then, from activite to set to textview - just do smthing like
final TextView tvphone = (TextView) findViewById(R.id.saved_phone);
String saved_phone = GetPhoneAddress();
if (saved_phone.length()>0){
tvphone.setText(saved_phone);
}
This function will read your whole file, and set it to the parameter TextView as text, if this is what you want. Your code is trying to write the TextViews content to a file, it's not reading it.
public void loadToTextView(TextView textView) throws Exception
{
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path, "filename.file");
textView.setText(new Scanner(file).useDelimiter("\\Z").next());
}
Be careful, you will need to handle the Exception, that this function might throw.
This method will read each line into a StringBuffer.
Then just call setText(contentsOfFile) on your TextView.
BufferedReader fileReader = new BufferedReader(new FileReader("/mnt/sdcard/agenda.file"));
StringBuilder strBuilder = new StringBuilder();
String line;
while((line = fileReader.readLine()) != null)
{
strBuilder.append(line);
}
fileReader.close();
strBuilder.trimToSize();
String contentsOfFile = strBuilder.toString();
What I am trying to accomplish is to read a file line by line and store each line into an ArrayList. This should be such a simple task but I keep running into numerous problems. At first, it was repeating the lines when it was saved back into a file. Another error which seems to occur quite often is that it skips the try but doesn't catch the exception? I have tried several techniques but no luck. If you have any advice or could provide help in anyway it would be greatly appreciated. Thank you
Current code:
try{
// command line parameter
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
Toast.makeText(this, "Could Not Open File", Toast.LENGTH_SHORT).show();
}
fileList.add(theContent);
//now to save back to the file
try {
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
There is a very simple alternative to what you are doing with Scanner class:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
Why do you have fileList.add(theContent) after the try/catch? I don't see what the point of that is. Remove that line and see if it helps.
Example, I just tested this code on my local machine (not android but should be the same)
import java.io.*;
import java.util.ArrayList;
class FileRead
{
public static void main(String args[])
{
ArrayList<String> fileList = new ArrayList<String>();
final String file = "textfile.txt";
final String outFile = "textFile1.txt";
try{
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
try {
FileWriter writer = new FileWriter(outFile);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
System.err.println("Error: " + error.getMessage());
}
}
}
After I ran this the 2 files had no differences. So my guess is that line may have something to do with it.