问题
I want to store 8 integers into a .csv file(the filename will be taken as an input from a EditText) and retrieve them when I want to.
回答1:
To get the filename you can use this:
EditText fileNameEdit= (EditText) getActivity().findViewById(R.id.fileName);
String fileName = fileNameEdit.getText().toString();
Then write the file on disk:
try {
String content = "Separe here integers by semi-colon";
File file = new File(fileName +".csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
To read the file:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName+".csv"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Then to have the Integers you can use split function:
String[] intArray = sCurrentLine.split(";");
回答2:
Opencsv doesn't work on Android due to JDK issue.
If you see simular to the following:
05-04 16:13:31.821 25829-25829/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pk.opencsvpoc, PID: 25829 java.lang.NoClassDefFoundError: Failed resolution of: Ljava/beans/Introspector;
It is because Android only ported over a subset of java.beans into its version of java. You can see a list of what is support at https://developer.android.com/reference/java/beans/package-summary
There are plans to switch over to reflection in opencsv 5.0 but I doubt it will remove all our dependencies on java.beans. For now the best suggestion for opencsv is to steer clear of the com.opencsv.bean classes until Android fully supports java.beans or we are successful in removing java.beans.
Another possibility is to try another csv library. I checked apache commons csv and super-csv and apache does not convert to beans but super-csv does using only reflection.
Source: https://sourceforge.net/p/opencsv/wiki/FAQ/#getting-noclassdeffounderror-when-using-android
回答3:
CSV is normal text file, where values are divided by character ";" so, you can write it using BufferedWriter for example.
BufferedWriter
来源:https://stackoverflow.com/questions/24259337/how-to-read-and-write-to-a-csv-file-in-android