Save/Read File in android - java

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

Related

How do you read and process a line that can have multiple objects on one line JAVA

I want to read a CSV file for a number of elements that can either be metal or non-metal and each line in the CSV file can have multiple elements. If it has multiple elements, all rows of the file will have that amount of elements. A valid line will look like:
<symbol,name,atomNum,mass,other/><symbol,name,atomNum,mass,other/>
where other is a character if its a nonmetal and double if its a metal. This is what I have done so far and am not sure how to read in multiple element objects on the line
public static void readValues(String fileName)
{
if (!constructed)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
lineNum = 0;
line = bufRdr.readLine();
while(line != null)
{
lineNum++;
elements[lineNum - 1] = processElements(line);
line = bufRdr.readLine();
System.out.println(elements);
}
fileStrm.close();
}
catch(IOException e)
{
if(fileStrm != null)
{
try
{
fileStrm.close();
constructed = true;
}
catch (IOException ex2)
{
}
}
System.out.print("error in file processing: " + e.getMessage());
}
}
}
private static Element processElements(String line)
{
char chr;
Element element;
String[] lineArray = line.split(",");
if(lineArray[4] == chr)
{
element = new NonMetal();
elements.setState(lineArray[4]);
}
else
{
element = new Metal();
element.setConduct(Double.parseDouble(lineArray[4]));
}
element.setSymbol(lineArray[0]);
element.setName(lineArray[1]);
element.setAtomNum(Integer.parseInt(lineArray[2]));
element.setMass(Double.parseDouble(lineArray[3]));
return elements;
}
I have a super element class and two subclasses, metal and nonmetal, each containing the standard methods for a class
You could use a regex to identify a group between < and />, while processing the line.
<(\w+),(\w+),(\w+),(\w+),(\w+)\/>
https://regex101.com/r/bKnYJZ/1/
String line = "<symbol,name,atomNum,mass,other/><symbol,name,atomNum,mass,other/>";
String regex = "<(\\w+),(\\w+),(\\w+),(\\w+),(\\w+)\\/>";
Matcher matcher = Pattern.compile(regex)
.matcher(line);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
System.out.println(matcher.group(5));
}
You could put this code into your processElements method to identify each element between < />
Aside of your problem, I suggest the use of try-resource-close for an easier and shorter resource handling.
try(FileInputStream fileStrm = new FileInputStream(fileName);
InputStreamReader rdr = new InputStreamReader(fileStrm);
BufferedReader bufRdr = new BufferedReader(rdr))
{
// here your code and no need to take care of resource closing...
}
catch(IOException e)
{
System.out.print("error in file processing: " + e.getMessage());
}

splitting of csv file based on column value in java

I want to split csv file into multiple csv files depending on column value.
Structure of csv file: Name,Id,Dept,Course
abc,1,CSE,Btech
fgj,2,EE,Btech
(Rows are not separated by ; at end)
If value of Dept is CSE or ME , write it to file1.csv, if value is ECE or EE write it to file2.csv and so on.
Can I use drools for this purpose? I don't know drools much.
Any help how it can be done?
This is what I have done yet:
public void run() {
String csvFile = "C:/csvFiles/file1.csv";
BufferedReader br = null;
BufferedWriter writer=null,writer2=null;
String line = "";
String cvsSplitBy = ",";
String FileName = "C:/csvFiles/file3.csv";
String FileName2 = "C:/csvFiles/file4.csv";
try {
writer = new BufferedWriter(new FileWriter(FileName));
writer2 = new BufferedWriter(new FileWriter(FileName2));
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] values=line.split(cvsSplitBy);
if(values[2].equals("CSE"))
{
writer.write(line);
}
else if(values[2].equals("ECE"))
{
writer2.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
writer.flush();
writer.close();
writer2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1) First find column index using header row or if header is not present then by index
2) Follow below algorithm which will result map of key value where key is column by which split is performed
global resultMap;
Method add(key,row) {
data = (resultMap.containsKey(key))? resultMap.get(key):new ArrayList<String>();
data.add(row);
resultMap.put(key, data );
}
Method getSplittedMap(List rows) {
for (String currentRow : rows) {
add(key, currentRow);
}
return resultMap;
}
hope this helps.
FileOutputStream f_ECE = new FileOutputStream("provideloaction&filenamehere");
FileOutputStream f_CSE_ME = new FileOutputStream("provideloaction&filenamehere");
FileInputputStream fin = new FileinputStream("provideloaction&filenamehere");
int size = fin.available(); // find the length of file
byte b[] = new byte[size];
fin.read(b);
String s = new String(b); // file copied into string
String s1[] = s.split("\n");
for (int i = 0; i < s1.length; i++) {
String s3[] = s1[i].split(",")
if (s3[2].equals("ECE"))
f_ECE.write(s1.getBytes());
if (s3[2].equals("CSE") || s3.equals("EEE"))
f_CSE_ME.write(payload.getBytes());
}

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");

very long string as a response of web service

I am getting a really long string as the response of the web service I am collecting it in the using the StringBuilder but I am unable to obtain the full value I also used StringBuffer but had no success.
Here is the code I am using:
private static String read(InputStream in ) throws IOException {
//StringBuilder sb = new StringBuilder(1000);
StringBuffer sb = new StringBuffer();
String s = "";
BufferedReader r = new BufferedReader(new InputStreamReader( in ), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
s += line;
} in .close();
System.out.println("Response from Input Stream Reader >>>" + sb.toString());
System.out.println("Response from Input S >>>>>>>>>>>>" + s);
return sb.toString();
}
Any help is appreciated.
You can also split the string in array of strings in order to see all of them
String delimiter = "put a delimiter here e.g.: \n";
String[] datas=sb.toString().split(delimiter);
for(String string datas){
System.out.println("Response from Input S >>>>>>>>>>>>" + string);
}
The String may not print entirely to the console, but it is actually there. Save it to a file in order to see it.
I do not think that your input is too big for a String, but only not shown to the console because it doesn't accept too long lines. Anyways, here is the solution for a really huge input as characters:
private static String[] readHugeStream(InputStream in) throws IOException {
LinkedList<String> dataList = new LinkedList<>();
boolean finished = false;
//
BufferedReader r = new BufferedReader(new InputStreamReader(in), 0xFFFFFF);
String line = r.readLine();
while (!finished) {
int lengthRead = 0;
StringBuilder sb = new StringBuilder();
while (!finished) {
line = r.readLine();
if (line == null) {
finished = true;
} else {
lengthRead += line.length();
if (lengthRead == Integer.MAX_VALUE) {
break;
}
sb.append(line);
}
}
if (sb.length() != 0) {
dataList.add(sb.toString());
}
}
in.close();
String[] data = dataList.toArray(new String[]{});
///
return data;
}
public static void main(String[] args) {
try {
String[] data = readHugeStream(new FileInputStream("<big file>"));
} catch (IOException ex) {
Logger.getLogger(StackoverflowStringLong.class.getName()).log(Level.SEVERE, null, ex);
} catch (OutOfMemoryError ex) {
System.out.println("out of memory...");
}
}
System.out.println() does not print all the characters , it can display only limited number of characters in console. You can create a file in SD card and copy the string there as a text document to check your exact response.
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Responsefromserver");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, "response.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(totalResponse);
writer.flush();
writer.close();
}
catch(IOException e)
{
System.out.println("Error:::::::::::::"+e.getMessage());
throw e;
}

Categories