Reputation: 399
longlat files:
101.2425101.2334103.345
The coding have algorithm like this:
ArrayList<String> getDifferenceList(String filePath) {
File f = new File("longlat.txt");
String line, x1 = null, x2= null, x3 = null;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(new FileReader(f));
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split("");
x1 = (parts[0]);
x2 = (parts[1]);
x3 = (parts[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> ret = new ArrayList<String>();
FileWriter writer;
if (x1 == null || x1.isEmpty()
|| x2 == null || x2.isEmpty()
|| x3 == null || x3.isEmpty()) {
ret.add(x1);
ret.add(x2);
ret.add(x3);
return ret;
}
int index = 0;
while (index < x1.length()
&& index < x2.length()
&& index < x3.length()) {
if (x1.charAt(index) != x2.charAt(index)
|| x1.charAt(index) != x3.charAt(index)) {
break;
}
index++;
}
ret.add(x1.substring(index, x1.length()));
ret.add(x2.substring(index, x2.length()));
ret.add(x3.substring(index, x3.length()));
return ret;
}
The values need to be stored into text file are inside the arraylist of ret.
I've tried :
FileWriter writer = new FileWriter("lalala.txt");
for(String str: ret) {
writer.write(str);
} writer.close();
I put the above coding at the top of :
ret.add(x1.substring(index, x1.length()));
Problem : Nothing shown when I click a button "Show lalala text".
and also tried :
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput ("lalala.txt",MODE_APPEND));
String text =(ret);
out.write(text);
out.write('\n');
out.close();
}
catch (java.io.IOException e) {
Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show
();}
}
I put the above coding at the top of :
ret.add(x1.substring(index, x1.length()));
Problem : Error at 'ret'. It said "Type mismatch: cannot convert from ArrayList to String"
I don't know how to take the arraylist and stored them into text file. Please give me some ideas, thanks.
Upvotes: 0
Views: 6568
Reputation: 2444
You are writing file before writing to your array List ret
I put the above coding at the top of :
ret.add(x1.substring(index, x1.length()));
Your ret is empty before this line. Your if-condition evaluates true then it actually returns from there. if-condition evaluates false. then you have empty array list.
There fore write to file after you have fully filled your arrayList.
i.e. just before return statement.
return ret;
Upvotes: 0
Reputation: 62884
ArrayList<String>
cannot be cast to String
.
You can write the content of the ArrayList
to a file in this way:
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("lalala.txt"));
for (String text : ret) {
out.writeln(text);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
out.close();
}
}
Upvotes: 1