I am building an app which needs to read and edit items from a .csv file.
I can place the .csv in the assets folder but would rather the ability to search for it in the external storage as it will change regularly.
A friend has given me this code for placing it in the assets folder, but I am relatively new to android and this code doesn't make sense to me and I cant get it to work.
public ArrayList<String> Job = new ArrayList<String>();
try {
is = res.getAssets().open("Job.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
Job.add(line);
} catch (IOException ex) {
// handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// handle exception
}
}
Related
I have downloaded a txt file from Firebase, and I have the path and everything, and I'm trying to convert this file into a String, so I can set all the content of the file to another method
i have tried this
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myTxtFile));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
Log.e("OUTPUTSTRING",""+br);
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
but in my log I cant see the content of the file, instead, it returns this
java.io.BufferedReader#5eb1add
That's because you're logging br which is an object of BufferedReader. You probably want to build the string using text.toString() and log it.
I'm a new student working on an android application. The application is almost done and works fine.
The app uses a property list to generate it's content. At this moment it uses a .plist file located in the assets folder. Ideally I want this .plist file to be retrieved from an URL. However i'm stuck on this part for a few days now.
Could you please advise me in how to realise retrieving and using the file from an URL. Any advice is welcome!
In my code we see how I currently read the .plist file. I don't think the parsing of the response is required info for my question:
public class PListHelper {
/**
* PlayList reader from assets
*
* #return string of p-list file
*/
public static String readPlayListFromAssets(Context context) {
StringBuffer sb = new StringBuffer();
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(context.getAssets().open("restaurant.plist")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException ex) {
ex.printStackTrace();
}
}
Log.i("Main", "input: "+sb.toString());
return sb.toString();
}
Have a look at URLConnection
Also, in the future, avoid using .plist as it something specific to ios and osx. By using another format (like json) you won't have to implement your own parsing.
I am developing an android app in netbeans. I am trying to read CSV file using opencsv. When I put the file in resources folder and try to read it from there, there's an error while building saying invalid resource directory. Where should I store csv file so that it can be read each time the app starts?
you should put csv file in assets folder ..
InputStreamReader is = new InputStreamReader(getAssets()
.open("filename.csv"));
BufferedReader reader = new BufferedReader(is);
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
}
Some advices;
Create an object for holding one row data into the csv. ( Ex: YourSimpleObject . It provides you to manage the data easily.)
Read file row by row and assign to object. Add the object to list. (Ex: ArrayList<YourSimpleObject >)
Code:
private void readAndInsert() throws UnsupportedEncodingException {
ArrayList<YourSimpleObject > objList= new ArrayList<YourSimpleObject >();
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("questions/question_bank.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
StringTokenizer st = null;
try {
while ((line = reader.readLine()) != null) {
st = new StringTokenizer(line, ",");
YourSimpleObject obj= new YourSimpleObject ();
//your attributes
obj.setX(st.nextToken());
obj.setY(st.nextToken());
obj.setZ(st.nextToken());
obj.setW(st.nextToken());
objList.add(sQuestion);
}
} catch (IOException e) {
e.printStackTrace();
}
}
As an alternative, take a look at uniVocityParsers. It provides a vast number of ways to parse delimited files. The example bellow loads a Csv File (see in the picture below) from a res/raw folder into a InputStream object, and read it in a colunar manner (a map where key=Column & value=ColumnValues).
calendario_bolsa.csv
//Gets your csv file from res/raw dir and load into a InputStream.
InputStream csvInputStream = getResources().openRawResource(R.raw.calendario_bolsa);
//Instantiate a new ColumnProcessor
ColumnProcessor columnProcessor = new ColumnProcessor();
//Define a class that hold the file configuration
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setProcessor(columnProcessor);
//Creates a new CsvParser, passing the settings into its construtor:
CsvParser csvParser = new CsvParser(parserSettings);
//Calls parse method, instantiating an InputStreamReader, passing to its constructor the InputStream object
csvParser.parse(new InputStreamReader(csvInputStream));
//Gets the csv data as a Map of Column / column values.
Map<String, List<String>> columnarCsv = columnProcessor.getColumnValuesAsMapOfNames();
To add univocityParsers into your Android Project:
compile group: 'com.univocity', name: 'univocity-parsers', version: '2.3.0'
Using opencsv:
InputStream is = context.getAssets().open(path);
InputStreamReader reader = new InputStreamReader(is, Charset.forName("UTF-8"));
List<String[]> csv = new CSVReader(reader).readAll();
you may use this code
try {
InputStream csvStream = assetManager.open(CSV_PATH);
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvReader = new CSVReader(csvStreamReader);
String[] line;
// throw away the header
csvReader.readNext();
while ((line = csvReader.readNext()) != null) {
questionList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
you may download csvreader file from
http://sourceforge.net/projects/opencsv/files/latest/download
and import in your project
I just want to delete 2 lines of text from a text file that I created. Currently, this is what I'm trying to get rid of the 2 lines:
private void deleteDataFromFile(String title, String Date) {
try {
//open the file
FileInputStream myIn= openFileInput(FILENAME);
//the reader given the input file stream.
InputStreamReader inputReader = new InputStreamReader(myIn);
//Aftert he inputstream is open, need also a bufferedReader
BufferedReader BR = new BufferedReader(inputReader);
//holds a line of input
String line;
//used for only erasing one date.
int counter = 0;
while ((line = BR.readLine()) != null && counter < 1) {
if (line.equals(title)) {
line.replace(title, "" + "\n");
line = BR.readLine();
line.replace(Date, "" + "\n");
counter++;
}
}
BR.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I realize that since I'm using the replace function on a string it has no effect on the actual file itself, but I can not find any other function in the IO library to affect the text file. What I'm thinking about doing is creating a new file on the phone with the exact contents of this file and just deleting the 2 lines from it. That seems troublesome and inefficient though, and I'd like to avoid it. Any suggestions?
I am trying to do what FileWriter.println() and BufferedReader.readLine() do in Android, but in android they only allow writing it into the sdcard using those method.
I need to write some integer values into the file and then read it line by line at a later time. Some of the file operation methods I found require the length of the data read to be specified, which is not possible.
Can anyone point me to the right method? Preferably with an example of the usage...
Regards
You can write to the SD card by using this path, "\sdcard\file_name"
and read it this way,
InputStream instream = null;
as
InputStream instream = openFileInput("/sdcard/filename");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
try {
while (( line = buffreader.readLine()) != null) {
Log.i(TAG, "line = "+line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// close the file again
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}