I have a requirement that I need to append block of a file to other file.
let say I have 100 lines in source file and I need to append the 50 lines from the bottom to destination file.
To navigate to the 50th line I using .readLine() of the BufferedReader.
Once I reached to 50 th line I want to append remaining content to the destination file.
I don't want to append line by line as it is consuming much time.
Please help me how to do that..
Please provide a code snippet if possible.
read the file line by line and append in StringBuffer object
for eg
StringBuffer lineBuffer = new StringBuffer();
String line = "";
while((line=br.readLine())!=null){
///// any condition or anything you want to do
lineBuffer.append(line);
}
now after you get the lines into the stringbuffer object write this into another file
Related
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 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 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?
I want to read the last 2 lines in some files, and if the content of second last line matches a specific string, then delete the last line only.
Also, after the above operation, 2 lines of data have to be appended to the end of the modified file. I saw other questions on SO that deal with different parts of my problem, but is there an easy way of doing all of the above with minimal code, preferably in a single function? (I can combine the different functions available at SO but that would be messy...)
I would recommend you to do it "in memory". It's easy to read line by line into a List, check the last lines and update the lines and write it back to the file.
Example:
public static void main(String[] args) throws IOException {
String fileName = "test.txt";
List<String> lines = new ArrayList<String>();
// read the file into lines
BufferedReader r = new BufferedReader(new FileReader(fileName));
String in;
while ((in = r.readLine()) != null)
lines.add(in);
r.close();
// check your condition
String secondFromBottom = lines.get(lines.size() - 2);
if (secondFromBottom.matches("Hello World!")) {
lines.remove(lines.size() - 1);
lines.add("My fixed string");
}
// write it back
PrintWriter w = new PrintWriter(new FileWriter(fileName));
for (String line : lines)
w.println(line);
w.close();
}
Note: No exception handling is done in the example above... you need to handle cases where the file for example doesn't contain two lines and other problems!
If you have really big files and perfomance is an issue the way to go is to use a RandomAccessFile and read backwards looking for the line termination bytes to determine where the last two lines begin. Otherwise use dacwe's approach.
As Gandalf said you can:
take RandomAccessFile,
use method seek(long) to jump forward and read those lines. But you won't know exactly how big the jump should be.
to delete last lines you need the position of begin of last line so before reading each line store their file pointer position (method getFilePointer()). Deleting to that position you use setLength(long).
My example of reading and deleting last lines you have here:
Deleting the last line of a file with Java
Useful can be also:
Quickly read the last line of a text file?
I have a delimited file which can contain around millions of records , now I want to delete the first line from the delimited file before processing it further.
The length of the first line is variable , it differs as per the file type.. now I have done a readup on the FileChannel and RandomAccessFile which have been suggested as the best ways to delete the first line.
But I am unable to figure it out , as to how to get the length of the first line and delete it.
Don't delete it, just read-and-ignore.
If you have to prepare the file because the file processing units can't handle a file with an incorrect first line, then you'll have to read and rewrite it. There is no I/O operation available that can delete contents from file in the filesystem.
use readLine() to read line by line , just ommit first line and consider others in processing
Thanks for the inputs. Depending on the same , I figured out a solution to remove the first line from the delimited pipe file.
Mentioned below is a code snippet
RandomAccessFile raf = new RandomAccessFile("path to ur delimited file", "rw");
FileChannel fileChannel = raf.getChannel();
raf.readLine();
raf.seek(raf.getFilePointer());
int len = (int) (raf.length() - raf.getFilePointer());
byte[] bytearr = new byte[len];
raf.readFully(bytearr, 0, len);
fileChannel.truncate(0);
raf.write(bytearr,0,len);
You could use a BufferedReader and use BufferedReader.readLine() to "delete" the first line before processing. From here you could continue to process the rest of the lines or store them into a file to process later. The latter option might not be the most efficient option available to you.