Save ArrayList<String> to text file - java

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.

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();
}
}

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;

Related

file handling deleting record after 2nd use

when i run the program the second time my Record.txt gets empty .
i think i'm getting this error in the file reader but i dont know what to do with it.
if you guys can give me a hint i'll appreciate it.
File file = new File("D:\\Program Files\\Oracle\\program\\Record.txt");
if (file.length() <= 0) {
try {
FileReader fr = new FileReader(
"D:\\Program Files\\Oracle\\program\\inventory.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
while ((datas = br.readLine()) != null) {
String[] d = datas.split(",");
int a = Integer.parseInt(d[1]);
int b = Integer.parseInt(d[2]);
items.add(new list(d[0], a, b));
}
br.close();
fr.close();
} catch (IOException | NumberFormatException e) {
System.out.println("Error");
}
}
Iterator itemit = items.iterator();
try {
FileWriter fw = new FileWriter(
"D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedWriter bw = new BufferedWriter(fw);
itemit = items.iterator();
while (itemit.hasNext()) {
list l = (list) itemit.next();
System.out.println(l.ingname + l.qty + l.ingid);
if (item1 == 1 && l.ingid == 100) {
l.qty = l.qty - item1qty;
}
if (item2 == 1 && l.ingid == 200) {
l.qty = l.qty - item2qty;
}
bw.write(l.ingname + ":" + l.qty + ":" + l.ingid);
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException e) {
System.out.println("Error");
}
else{
try{
FileReader fr = new FileReader("D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
//System.out.println(file.length());
while((datas = br.readLine()) != null){
String[] d = datas.split(",");
int x = Integer.parseInt(d[1]);
items.add(new list(d[0],x));
}
br.close();
fr.close();
}catch(IOException | NumberFormatException e){
System.out.println("Error");
}
}
From the code parts you provided it looks like the items list is only filled with entries from inventory.txt if the Record.txt file is empty. If it is not empty (f.e. when running the program for a second time) items is probably empty and thus the content of Record.txt will overwritten.
Currently your code looks like this
if (Record.txt file is emtpy) {
read inventory file into items
}
write items to record file
// where is the corresponding if?!
else {
read Record.txt file
}
and is should probably look like this
if (Record.txt file is emtpy) {
read inventory file into items
write items to record file
}
else {
read Record.txt file
}

Save/Read File in android

I want to save to a file in android , Some of my arrayList that will be deleted after that.I already have two methods to write/read from android file here but the problem is I want the two methods do that:
the first method must save the element of arraylist then if I call it again it will not write the new element in the same line but write it in another line
The second must read a line (for example I give to the method which line and it returns what the lines contains)
The file looks like that :
firstelem
secondelem
thridelem
anotherelem
another ..
is this possible to do in android java?
PS: I don't need database.
Update
This is My methods :
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
// stringBuilder.append("\\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Using the save method you linked to you can create the text to save with a StringBuilder:
public String makeArrayListFlatfileString(List<List<String>> listOfLists)
{
StringBuilder sb = new StringBuilder();
if (!listOfLists.isEmpty()) {
// this assumes all lists are the same length
int listLengths = listOfLists.get(0).size();
for (int i=0; i<listLengths; i++)
{
for (List<String> list : listOfLists)
{
sb.append(list.get(i)).append("\n");
}
sb.append("\n"); // blank line after column grouping
}
}
return sb.toString();
}
To parse the contents from that same file (again assuming equal length lists and a String input):
public List<List<String>> getListOfListsFromFlatfile(String data)
{
// split into lines
String[] lines = data.split("\\n");
// first find out how many Lists we'll need
int numberOfLists = 0;
for (String line : lines){
if (line.trim().equals(""))
{
// blank line means new column grouping so stop counting
break;
}
else
{
numberOfLists++;
}
}
// make enough empty lists to hold the info:
List<List<String>> listOfLists = new ArrayList<List<String>>();
for (int i=0; i<numberOfLists; i++)
{
listOfLists.add(new ArrayList<String>());
}
// keep track of which list we should be adding to, and populate the lists
int listTracker = 0;
for (String line : lines)
{
if (line.trim().equals(""))
{
// new block so add next item to the first list again
listTracker = 0;
continue;
}
else
{
listOfLists.get(listTracker).add(line);
listTracker++;
}
}
return listOfLists;
}
For writing, just as Illegal Argument states - append '\n':
void writeToFileWithNewLine(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data + "\n");
outputStreamWriter.close();
}
catch (IOException e) { /* handle exception */ }
}
For reading (just the idea, in practice you should read the file only once):
String readLine(final int lineNo) {
InputStream in = new FileInputStream("file.txt");
ArrayList<String> lines = new ArrayList<String>();
try {
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line;
do {
line = reader.readLine();
lines.add(line);
} while(line != null);
} catch (Exception e) { /* handle exceptions */ }
finally {
in.close();
}
if(lineNo < lines.size() && lineNo >= 0) {
return lines.get(lineNo);
} else {
throw new IndexOutOfBoundsException();
}
}

New line after 12 chars java

I have a class which can read a file, modify it an write it to another file. The characters in the output are correct , the only problem is that the lines need to have a length of 12 chars.
How can I achieve this with my existing code?(I wrote a comment where in the code I want to do this)
My input file: http://gyazo.com/13fe791d24ef86e29ab6a6e89d0af609
The current output: http://gyazo.com/cc195c1d59a9d1fe3b4f2c54e71da8eb
The output I want : http://gyazo.com/04efcbb05c5d56b6e28972feb8c43fb8
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
}
/* if a * is followed by * change them to a ! */
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
// get last character from stringbuilder and delete
buf.deleteCharAt(buf.length()-1);
/* start with a new line if the line length is bigger than 12 - how to do it? */
//???
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/uitvoer1.txt");
// 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();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}}
Would something along these lines help?
for (int i=13;i<buf.size();i+=13) {
buf.insert(i, '\n');
i++; // to account for the newline char just added
}
The numbers used may not be correct, either because of misunderstanding of the question or because it isn't tested.
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
There will be an java.lang.ArrayIndexOutOfBoundsException at the end of the loop when you you call index+1

Start with new line after certain amount of characters in java

I have a program which reads a file I can change the content of this file and after that it's written to another file. The input file looks like this: http://gyazo.com/4ee1ade01378238e2c765e593712de7f and the output has to look like this http://gyazo.com/5a5bfd00123df9d7791a74b4e77f6c10 my current output is http://gyazo.com/87a83f4c6d48aebda3d11060ebad66c2 so how to change my code that it's starts a new line after 12 characters? Also I want to delete the last !.
public class readFile {
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
//buf.append(System.getProperty("line.separator"));
}
/* start with a new line if the line length is bigger than 12 - in progress*/
/* I know this if doesn't work but how to fix it? */
if (buf.length()>12){
buf.append(System.getProperty("line.separator"));
}
/* if a * is followed by * change them to a !*/
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
//buf.deleteCharAt(buf.length()-1);
}
// get last character from stringbuilder and delete
//buf.deleteCharAt(buf.length()-1);
}
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/test.txt");
// 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();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Update the code in which while reading the file you will take the decision :
int sevenCount = 0;
int fourteenCount = 0;
int data = 0;
while ((data = reader.read()) != -1) {
sevenCount++;
fourteenCount++;
if(sevenCount==7)
{
buf.append("-"); // append - at every 7th character
sevenCount = 0;
}
if(fourteenCount==14)
{
buf.append("\n"); // change line after evrry 14th character
fourteenCount = 0;
}
if(((char)data) == '*')
{
char c = '!'; //Change the code when char contain *
data = (int)c;
}
else
{
buf.append((char)data);
}
}
If you want to insert a newline in a string every 12 chars:
str = str.replaceAll(".{12}", "$0\n");

read specific substring with condition

I have this from text file:
134.897 134.4565 135.134
I read them using :
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
String x1 = (parts[0]);
String x2 = (parts[1]);
String x3 = (parts[2]);
From the String in the text file :
134.897
134.4565
135.134
I just want to take the different number between these three number :
4.897
4.4565
5.134
Given more example :
Text file :
101.435
101.423
101.322
Number I want to take :
435
423
322
My plan is I want to compare each number with others,
101.435//x1
101.423//x2
101.322//x3
if x1.substring(0)=x2.substring(0)=x3.substring(0)
then remove substring(0).
I want to loop this "if" condition until the substring are not same.
Please give me some idea, thanks
Here's the skeleton of an algorithm that could be used:
List<String> inputs = ...;
int index = 0;
while (allTheStringsHaveTheSameCharacterAtIndex(inputs, index)) {
index++;
}
List<String> outputs = takeSubstringOf(inputs, index);
I'll let you fill the blanks, which are very easy to implement with the methods offered by the String class, and loops.
You didn't answer #Steve about scenario of different length of numbers, I'll assume you want to compare numbers according to characters order. Also, I assume that the file always contains three strings in one line, saperated by one white space.
Given this, I hope this helps:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FindDifference {
static File f = null;
ArrayList<String> inputs = new ArrayList<String>();
static String x1 = null;
static String x2 = null;
static String x3 = null;
private static ArrayList<String> getDifferenceList() {
ArrayList<String> ret = new ArrayList<String>();
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;
}
public static void main(String[] args) {
if (args.length > 0) {
f = new File(args[0]);
} else {
System.out.println("Please supply file path.");
return;
}
String line;
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> output = getDifferenceList();
try {
System.out.println(output.get(0));
System.out.println(output.get(1));
System.out.println(output.get(2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I made it SSCCE. You can use only getDifferenceList (supplying x1,x2,x3 as fields) in your code (delete "static" wherever needed).
EDIT
As I said, you can use getDifferenceList in any scope (including Android application). I copy this method separately, simply copy-paste it into any class you want, and call it passing the file path:
ArrayList<String> getDifferenceList(String filePath) {
File f = new File(filePath);
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>();
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;
}

Categories