// 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.
Related
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
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
I have a large .csv file (about 300 MB), which is read from a remote host, and parsed into a target file, but I don't need to copy all the lines to the target file. While copying, I need to read each line from the source and if it passes some predicate, add the line to the target file.
I suppose that Apache CSV ( apache.commons.csv ) can only parse whole file
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
CSVParser csvFileParser = new CSVParser("filePath", csvFileFormat);
List<CSVRecord> csvRecords = csvFileParser.getRecords();
so I can't use BufferedReader. Based on my code, a new CSVParser() instance should be created for each line, which looks inefficient.
How can I parse a single line (with known header of the table) in the case above?
No matter what you do, all of the data from your file is going to come over to your local machine because your system needs to parse through it to determine validity. Whether the file arrives via a file read through the parser (so you can parse each line), or whether you just copy the entire file over for parsing purposes, it will all come over to local. You will need to get the data local, then trim the excess.
Calling csvFileParser.getRecords() is already a lost battle because the documentation explains that that method loads every row of your file into memory. To parse the record while conserving active memory, you should instead iterate over each record; the documentation implies the following code loads one record to memory at a time:
CSVParser csvFileParser = CSVParser.parse(new File("filePath"), StandardCharsets.UTF_8, csvFileFormat);
for (CSVRecord csvRecord : csvFileParser) {
... // qualify the csvRecord; output qualified row to new file and flush as needed.
}
Since you explained that "filePath" is not local, the above solution is prone to failure due to connectivity issues. To eliminate connectivity issues, I recommend you copy the entire remote file over to local, ensure the file copied accurately by comparing checksums, parse the local copy to create your target file, then delete the local copy after completion.
This is a late response, but you CAN use a BufferedReader with the CSVParser:
try (BufferedReader reader = new BufferedReader(new FileReader(fileName), 1048576 * 10)) {
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader);
for (CSVRecord line: records) {
// Process each line here
}
catch (...) { // handle exceptions from your bufferedreader here
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.
I want to specifically overwrite data in a file starting from a given line.
Suppose that I find out that I have to write some data in the file from line x ( I have already found x) . How would I overwrite everything after there.
Also is there a function that would directly take my line and string and overwrite the file.
An alternate approach would be, read the file line by line by scanner class (as described below), store those lines into any variable, say, arraylist, then appennd your new string once you have read the lines and write the whole list into a new file.
Example:
File file = new File("file.txt");
Scanner scanner = new Scanner(file).useDelimiter("\n");
String line = scanner.next();
//Store in the list
//Append the new lines
//Write the whole list into a new file