Hi All,
I am getting a text file say "a.txt" generated from a tool which gives me some kind of logs. I want to read the data from "a.txt" line by line and write it into "b.txt", deleting the line which I have read from "a.txt" and about to write in "b.txt".
Also there should be no speed mismatch among read and write operation because it might cause to lost of data.
Can any one please help me on that technically with code.
package remotefileaccess;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
public class deleteAndReadFile
{
public static void main(String[] args)
{
//Enter name of the file here
String filename="C:\\D\\myfiles\\ab.txt";
String filename1="C:\\D\\myfiles\\pq.txt";
//Enter starting line here
int startline=1;
//Enter number of lines here.
int numlines=1;
deleteAndReadFile now=new deleteAndReadFile();
now.delete(filename,startline,numlines,filename1);
}
void delete(String filename, int startline, int numlines,String filename1)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename1, true), "UTF-8"));
//String buffer to store contents of the file
StringBuffer sb=new StringBuffer("");
Scanner input = new Scanner(new File(filename));
//Keep track of the line number
int linenumber=1;
String line;
while(input.hasNextLine()){
while((line=br.readLine())!=null)
{
//Store each valid line in the string buffer
if(linenumber<startline||linenumber>=startline+num lines)
{ sb.append(line);
sb.append(System.getProperty("line.separator"));
}
else
{
writer.append("**"+line);
writer.append(System.getProperty("line.separator") );
}
startline++;
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
writer.close();
FileWriter fw=new FileWriter(new File(filename));
//Write entire string buffer into the file
fw.write(sb.toString());
fw.close();
}
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
Thank you
Rohant