How to replace a line in a text file using Java? - java

I have a text file with various key value pairs separated with a '--'.
Below is the code I have so far
File file = new File("C:\\StateTestFile.txt");
BufferedWriter out = new BufferedWriter(file.getAbsolutePath());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("content_style")) {
//Write to the line currently reading and save back to the file
}
}
br.close();
out.close();
What I would like to do is read this text file and replace the value of a specific line with something I specify. So id want to find the 'content_style' line and replace 'posh' with 'dirty'.
How can I do this?

simply use:
line = line.replaceAll("posh", "dirty"); // as strings are immutable in java

This can be done in-place on a single file only if you are sure that the string you are replacing is exactly the same length in bytes as the string that replaces it. Otherwise, you can't add or delete characters in a single file, but you can create a new file.
Open the source file for reading.
Open the destination file for writing.
Read each line in the source file, use replaceAll, and write it to the destination file.
Close both files.
Alternate method that preserves the key-value semantics:
Open the source file for reading.
Open the destination file for writing.
Split each line in the source file into a key and value pair. If the key equals "content_style", write the key and "dirty" to the destination file. Otherwise write the key and value.
Close both files.
Finally, delete the old file and rename the new file on top of the old one. If you're going to be doing key-value manipulations often, and you don't want to write out a new file all the time, it might be worth it to use a database. Look for a JDBC driver for SQLite.

Related

How to update data in a text file which is stored in local storage using java

I have text file in a local storage with some data. Now i need to update data for only selected line data.
This is my textfile data
Kumar
Gaaa
9394769487
Male
Un Married
Tue Jun 12 00:00:00 IST 1984
kumar#gmail.com
Kumar#1993
rtyhrty
India
here i am receiving new data from different fields.So i need to update
particular lines of data to related data only
ex: Here first line is Name=kumar,
i want to update Name=ajay
this is my reading logic and put all the values into HashMap object.
can you tell me any another process is there for putting all lines of data to particular key in a Map object.
String temp;
String[] line=new String[15];
InputStream stream=new FileInputStream(path);
BufferedReader reader =new BufferedReader(new InputStreamReader(stream));
while((temp = reader.readLine()) != null)
{
for(int j=0; j<line.length ;j++)
{
line[j]=reader.readLine();
String fname=line[0];
String lname=line[1];
String mobile=line[2];
String gender=line[3];
String marry=line[4];
String dob=line[5];
String email=line[6];
String pwd=line[7];
String address=line[8];
String country=line[9];
String idcard=line[10];
String idfile=line[11];
String addcard=line[12];
String addfile=line[13];
map.put("fname",fname);
map.put("lname",lname);
map.put("mobile",mobile);
map.put("gender",gender);
map.put("marry",marry);
//map.put("dob",dob);
map.put("email",email);
map.put("address",address);
map.put("country",country);
map.put("idcard",idcard);
map.put("idfile",idfile);
map.put("addcard",addcard);
map.put("addfile",addfile);
}
}
stream.close();
reader.close();
You can use map or read line by line both are efficient based on below scenario
If reading the file one time and editing the file as and when requirement comes is what you need then storing the data in static map(class level static variable) is your best solution.By doing this you don't need to read the file again and again whenever the modification for file comes change the value in map and overwrite the whole map data to file
If you want to read the file each time there is a modification request then the best thing to do is to read it line by line and modify the line for which the request came and then overwrite the file.It does not make sense to store the file data in map each time if you are going to read the file at every request.
Hope This Helps !!
I would suggest reading the file line by line, change what lines you need to change and write all lines to a new file, then delete the old file and rename new file. Unless the file is very large and you only need to change first few lines.
Read the file into a map
Alter the map
Write the map into the file

Java split one line file

I have just relised that I have a file where only one line exists with a long string. This file (line) can be300MB heavy.
I would like stream some data from this string and save in another file
i.e the line from the file would look like:
String line = "{{[Metadata{"this, is my first, string"}]},{[Metadata{"this, is my second, string"}]},...,{[Metadata{"this, is my 5846 string"}]}}"
Now I would like to take 100 items from this string from one "Metadata" to another "Metadata", save it in the file and continue with the rest of the data.
So in the nutshell from one line I would like to get N files with i.e. 100 Metadata strings each
BufferedReader reader = new BufferedReader(new StringReader(line));
This is what I've got and I don't know what I can do with the reader.
Probably
reader.read(????)
but I don't know what to put inside :(
Can you please help

How to Handle String Encoding in JAVA(linux os)

I have one CSV file which contains many records. Noticed that some of the records contain French characters. My script reads each record and processes it and inserts the processed record in the XML. When we view the .csv file on terminal using VIM Editor on Fedora system, the French characters are displayed in correct format. But after processing the records these characters are not getting displayed properly. Also when such a record is printed on the console, it is not displayed properly.
For eg.
String in .csv file : Crêpe Skirt
String in XML : Cr�pe Skirt
code Snippet for Reading file.
BufferedReader file = new BufferedReader(new FileReader(fileLocation));
String line = file.readLine();
Kindly suggest a way to handle such issue.
You need to know what encoding the file is in (probably UTF-8) and then when you open the file in Java specify the same encoding.
try reading the file as UTF-8 file. And provide the encoding of your xml file as UTF-8 too
BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(your-file-path),"UTF-8"));
String line="";
while((line=reader.readLine())!=null) {
//Do your work here
}

File and Filewriter

I need a way to delete a line, im using this to write on the file:
FileWriter insert = new FileWriter(file, true);
PrintWriter out = new PrintWriter(insert);
out.println("1. Mario");
I made a thing that reads line by line but i've no idea how to delete the string that returns, is that even possible?
While you're reading in the lines of text write then lines you want to keep to a StringBuffer or StringBuilder then write the contents of the buffer/builder back to the file. Is there any specific reason that you're opening up the file for appending when you're wanting to remove lines of text from the file or am I missing something?

Java delete or modify one record in File

// Create file
FileWriter fstream = new FileWriter(fileName, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(c.toString());
//Close the output stream
out.close();
// Code I used to read record I am using | as a seperator name and id
String fileName = folderPath + "listCatalogue.txt";
String line = "";
Scanner scanner;
String name, id;
scanner = new Scanner(fileName);
System.out.println(scanner.hasNextLine());
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
StringTokenizer st = new StringTokenizer(line, "|");
name = st.nextToken();
id = st.nextToken();
catalogues.add(new Catalogue(name, id));
}
Above is the code to create file and read file, How can I do delete certain record, in File, what I have found from google is delete the file but not delete certain record example I provide name, if match delete this record. As well as modify that record? Is it possible to do modify record using File?
Deleting certain record in file is impossible for several reasons.
First, record is your application level term. File system knows only sequence of bytes. Second streams you are using to access file are abstractions that do not support deletion as well.
So, what's the solution.
You can read file record-by record and write other file record-by-record unless you see record you want to delete. Avoid writing this record to other file. This gives you effect of deletion. But this method is not effective for big files.
File streams support mark() and skip() methods. If you data structure allows retrieving the position of record you want to delete you can arrive to this position immediately by calling skip(). The problem is to delete. to solve it you should either create data structure that allows marking record as deleted. In this case you do not really delete record but just mark it as deleted. Other solution is to write special (e.g. null) values over the record but your reader have to be able to skip such null values.
This solution has disadvantage: if you remove many records the file is will not be smaller.
Variant: you can use RandomAccessFile API. You can also use FileChannel.

Categories