I am trying to read a file into an Array. The following code saves the file (I know it needs a clean up)
public void save() {
String text = Subreddit_Array_List.toString() + "\n";
FileOutputStream fos = null;
deleteFile("example.txt");
try {
try {
fos = openFileOutput(FILENAME, MODE_APPEND);
try {
fos.write (text.getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
} finally {
if (fos != null) {
try {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The input file looks like this:
[Test, Cats]
So either I have to try and save without the commas and per line or I need a way of separating the values from the commas. Any help would be much appreciated.
My Current Load code:
public void load() {
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
Subreddit_Array_List.add(text);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
maybe splitting by coma will be sufficient?
List<String> customList = Arrays.asList(text.split(","));
note it will leave brackets []
on start and end of first and last list item, and also white space on start (as coma is always followed by space), so you need to clean up a bit using trim
and replace
methods (or maybe split by ,
and substring text
removing first and last char if you are shure these will be brackets always)
edit: put my line in here
try {
fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
text = sb.toString();
// below line removes first and last character (brackets)
text = text.substring(1, text.length() - 1);
// text variable contains an array, split it by coma and space
List<String> customList = text.length() == 0 ?
new ArrayList<String>() : Arrays.asList(text.split(Pattern.quote(", ")));
Subreddit_Array_List.addAll(customList);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
note that customList
will contain two String
s: Test
and Cats