Android: Append to file instead of ovewriting - java

I am trying to append to a text file but for some reason it keeps overwriting it, here's my code:
File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt");
try {
if(!logFile.exists()) {
logFile.createNewFile();
}
StringBuilder text = new StringBuilder(); // build the string
String line;
BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file
while ((line = br.readLine()) != null) { // if not empty continue
text.append(line);
text.append('\n');
}
BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
output.write(text + "\n");
output.close();
alertDialog.show();
} catch (IOException ex) {
System.out.println(ex);
}
thank you in advance

use
new FileWriter(logFile, true)
Where the second parameter tells it to append, not overwrite.
Found in this question. In the related questions on the right.
Documentation can be found here

You need to use the other constructor of FileWriter that specifies whether the data is overwritten or appended. Use FileWriter(logFile, true) instead of what you have now :)

Related

Add Text To An Existing Text File

Hello I am new to Android development. I am developing an app as a training. So now my target is to add some new text to an existing text file.
For example: I have a text file in "sdCard/android.txt" and in this file there are some data written "I love android". Now I want to add some more texts "It is awesome" in a new line of that file.
Finally the android.txt ahould look like this:
I love android
It is awesome
So how can I achieve that?
You can just do it as you do it in Java.
try {
String fn = getExternalFilesDir(null) + File.separator + "android.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fn, true));
bw.write("\nIt is awesome\n");
bw.close();
// checking
BufferedReader br = new BufferedReader(new FileReader(fn));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
You can look at this example and use a BufferedWriter. When you execute File-Read or -Write operations, make sure to always use try/catch blocks.
public void appendText () {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Path-to-your-file", true));
bw.write("text-to-append");
bw.newLine();
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
You should definitely read about IO (Input-Output) Operations in Android/Java. https://docs.oracle.com/javase/tutorial/essential/io/
Good luck!

How to append a line in a file or before encountering newline character?

Input File:
Online_system_id
bank_details
payee
credit_limit
loan_amount
Online_system_id
bank_details
payee
credit_limit
loan_amount
Expected Output:
Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id
Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id
Below is the code given for reference.
I want to add a line after each record i.e before encountering the blank line.
What changes do I need to do?
String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if(!line.contains("proc_online_system_id")){
flag=1;
}
}
if(flag==1)
out.print("proc_online_system_id");
String line;
PrintStream out = null;
BufferedReader br = null;
try {
out = new PrintStream(new FileOutputStream(outputFile));
br = new BufferedReader(new FileReader(inputFile));
while((line=br.readLine())!=null){
if(line.trim().isEmpty()) {
out.println("proc_online_system_id"); //print what you want here, BEFORE printing the current line
}
out.println(line); //always print the current line
}
} catch (IOException e) {
System.err.println(e);
} finally {
try{
out.close();
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
And don't forget the out.close(); and br.close(); afterwards.
This solution stores only the current line in memory, as opposed to Dakkaron's answer, which is correct, but needs to store the whole file in memory (in a StringBuilder instance), before writing to file.
EDIT: After Vixen's comment, here is the link, in case you have java 7, and you want to use try with resources in your solution.
Try this code
String line;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if (!line.trim().isEmpty()){
line+="\n";
}
//System.out.println(line);
}
Buffer each block. So what you do is read the file line by line and store the content of the current block in a StringBuilder. When you encounter the empty line, append your additional data. When you did that with the whole file, write the content of the StringBuilder to the file.
String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if(!line.contains("proc_online_system_id")){
flag=1;
}
if (line.isEmpty() && flag==1) {
flag=0;
builder.append("proc_online_system_id\n");
}
builder.append(line).append("\n");
}
out.print(builder.toString());

Importing a text file in Android SDK

I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}

Reading a variable number of lines from a file

I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer

I want to edit part of a line in a text file

BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("Smokey")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\n");
} else {
bw.write(line+"\n");
}
}
}
catch (Exception e) {
return;
} finally {
try {
if(br != null){
br.close();
messagejLabel.setText("Error");
}
} catch (IOException e) {
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
When running the code above I end up with an empty file "tmpfiles.txt" and the file "files.txt is being deleted. can anyone help? I don't want to use a string to read the file. I would prefer to do it his way.
A quick test confirmed that not closing the writer as I wrote in my comment above actually produces the behavior you describe.
Just add
if (bw != null) {
bw.close();
}
to your finally block, and your program works.
I found some issue in your code.
First, this line seems not correct:
if (line.contains("Smokey")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\n");
it should be:
if (line.contains("Smokey;")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\r\n");
And, you should flush and close the bw after finish it.
if (bw != null){
bw.flush();
bw.close();
}
Correct me if I'm wrong.
The file is never written to because the writer was never "flushed". When closing the writer all the data in the buffer is automatically written to the file. Get used to standards with streams where you close them in a try-catch block.

Categories

Resources