How to delete a line in a .txt file using FileOutputStream? - java

I need to delete a line from a .txt file stored in the android device's internal storage. I am using
FileOutputStream fos = context.openFileOutput("file.txt", Context.MODE_APPEND);
to open the .txt file. I already know the line which is to be deleted. How to delete it? Sorry if this question is easy, I looked and couldn't find an answer on Google.

You can't easily remove a line of text from a file. You can overwrite it with other data which contains the same number of characters, but basically files don't support removing data from arbitrary locations in a file.
You probably want to:
Create a reader for the existing file
Create a writer for a new file
Copy one line at a time, skipping the line you want to delete
Close both the reader and the writer
Rename the old file out of the way
Rename the new file to the old filename
Delete the renamed old file
(Those steps make sure that even if something goes wrong, you never lose data.)

Related

Java: edit/remove a specific line (with streams) directly into the original file

This is my scenario: I have a huge .txt file (~16GB) that contains some lines that have to be removed (that can easily be found with a .contains()).
Obviously the idea of loading the whole file on RAM and explore it with a Scanner, then saving the results in a new .txt file is unfeasible (since I have 16GB of RAM).
I also know that with the streams I'm able to read the file line by line, avoiding the memory leak. What I don't know (and haven't been able to find) is wether it is possible to edit that specific line and put it back in its place into the file.
Otherwise, is it possible to just rewrite a new .txt file with just the "correct" lines in a similar way to the one that allows me to read line by line, so without loading the whole file in memory, since before or after it will become as huge as the original one?
Set up a Stream Reader that will be reading your file line by line, and a Stream writer that will be outputting to the new file. If the reader doesn't find the line to edit the writer simply writes that line to the new file. If the reader spots the line it wishes to edit, create a method to manipulate the line and return it, then have the Writer write that manipulated line rather than the original one.
You won't be allowed to access the same file with a Streamreader and Streamwriter.

appending mat file in java

I have a question about the com.jmatio.io package that I was hoping someone could answer. I am looking to write to a .mat file (using java) that may or may not already exist.
If it exists I would like to append the information to the end but if the file is not created I would like to create a new file and just add the contents to that.
My second write is overwriting the first but I would not like it to do this.
Any suggestions or solutions is gladly appreciated.
If you want to write multiple arrays to a new file you can achieve it using the MatFileIncrementalWriter. As it's explained in it's javadoc
An updated writer which allows adding variables incrementally for the life of the writer. This is necessary to allow large variables to be written without having to hold onto then longer than is necessary.
And it states clearly that you can't append to an existing file.
If you want to append to an existing file you might need
read variables from the existing file
write the existing variables back to the file using a MatFileIncrementalWriter
add new variables to the incremental writer
You need to write in append mode so the content get appended to the end to the file instead of overwriting.
File out = new File("out.mat");
try(FileWriter fw = new FileWriter(out, true); // true is for append
BufferedWriter bw = new BufferedWriter(fw)) {
// ...
}
If the file does not exist, it will be created.

append properties file from java

From java I want to read .properties file and if property is present I want to re-set the property again. lets say .properties file has entry password=123 now I want to check If password entry is there replace 123 with 567. but need to keep all content as it is. how to do that? please help
One solution I can think of rightaway is
Load all the properties from the base .properties file.
Create a new temp properties file and loop through the entries from original file to write the same in to new file. In the loop you can change the value of any property while writing it to a new file.
After the loop delete the original file and rename the temp file as original file.
This approach has couple of limitations,
Do not use it if you are really concerned about the file last modified/created date, since we are creating a whole new file here.
If the original file is too big, this approach may cause memory problems.
Hope this helps!

Delete file contents using RandomAccessFile

I have a file which contains lot of zeros and as per the requirement the zeros in the file are invalid. I am using RandomAccessFile api to locate data in the file. Is there way so that all the zeros can be removed from the file using the same api.
You'll have to stream through the file and write out the content, minus the zeros, to a separate temporary file. You can then close and delete the original and rename the new file to the old file name. That's your best alternative for this particular use case.
You can use RandomAccessFile to read the files' data, and when you reach a point where you need to change the data you can overwrite the existing number of bytes with equal number of bytes. It's iff the new value is exactly the same length as the old value.
With RandomAccessFile its difficult and equally complex when the size of two, the one being changed and the new value are different. It involves a lot of seeks, reads and writes to move data back
Try to read the whole file, change the bits you have to change and write a new file. You might process one line at a time or read the whole file into memory, modify it and write it all back out again. It is a good idea to perform the edit in the following manner:
Read file
Write to Temporary File [just to back-up]
Rename original to back-up
Work on Temporary file.
Remove Backup if you were successful.

In java, how do i edit 1 line of a text file?

Ok so I know the value of the line, I dont have the line number, how would I edit only 1 line?
Its a config file, i.e
x=y
I want a command to edit x=y to x=y,z.
or even x=z.
In Java you can use `Properties class:
app.config file:
x=y
java:
public void writeConfig() throws Exception {
Properties tempProp = new Properties();
tempProp.load(new FileInputStream("app.config"));
tempProp.setProperty("x", "y,z");
tempProp.store(new FileOutputStream("app.config"), null);
}
If you are using that configuration format, you might want to use
java.util.Properties
component to read/write on that file.
But if you just want to edit it by hand, you can just read the file line by line and match the variable you want to change.
One way to do it is to:
Read the file into memory; e.g. as an array of Strings representing the lines of the file.
Locate the String/line you want to change.
Use a regex (or whatever) to modify the String/line
Write a new version of the file from the in memory version.
There are many variations on this. You also need to take care when you write the new version of the file to guard against losing everything if something goes wrong during the write. (Typically you write the new version to a temporary file, rename the old version out of the way (e.g. as a backup) and rename the new version in place of the old one.)
Unfortunately, there is no way to add or remove characters in the middle of a regular text file without rewriting a large part of the file. This "problem" is not specific to Java. It is fundamental to the way that text files are modelled / represented on most mainstream operating systems.
Unless the new line has the exact same length as the old one, your best bet is to
Open a temporary output file
Read the config file, line by line
Search for your key
If you can't find it, just write the line you just read to the output file
If you can find it, write the new value to the temporary file instead
Until you hit EOF
Delete old file
Rename new file to the old file
IF your config file is small, you can also do the whole parsing/modification step in memory and then write the final result back to the config file, that way you skip the temporary file (although a temporary file is a good way to prevent corruption if something breaks while you write the file).
If this is not what you're looking for, you should edit your question to be a lot more clear. I'm just guessing what you're asking for.
If your data is all key and value pairs, for example ...
key1=value1
key2=value2
... then load them into a Properties object. Off the top of my head, you'll need a FileInputStream to load the properties, modify with myProperties.put(key, value) and then save the properties with the use of a FileOutputStream.
Hope this helps!
rh

Categories