Java, copying from file to another, line by line at interval
I have a file with 120 lines and I want to move them one by one to another file with an interval of, for example, 1 second, and to find after 10 seconds 10 lines in a new file.
But for my case, I run the program with 0 lines in new files to the end and then I find the data.
String sourceFileName = "D:\\oldfile.txt";
String destinationFileName = "D:\\newfile.txt";
if(evt.getSource() == btnProcess)
{
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader(sourceFileName));
pw = new PrintWriter(new FileWriter(destinationFileName));
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
Thread.sleep(1000);
}
br.close();
pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
Second, to process 4 files at the same moment at different intervals, do I need to use Threads? Thanks for your help.
source to share
When you write a text file, PrintWriter
doesn't write it to disk immediately. Instead, it stores data in a buffer in memory.
You can manually flush the buffer if you need data on disk. Immediately after, println()
call flush()
as shown below.
while ((line = br.readLine()) != null) {
pw.println(line);
pw.flush();
Thread.sleep(1000);
}
source to share
As for your second part, you can do something like this if you don't want to use streams:
public static void main(final String[] args) {
FileCopyDto[] files = new FileCopyDto[] {
new FileCopyDto("D:\\oldfile.txt", "D:\\newfile.txt", 5),
new FileCopyDto("D:\\oldfile2.txt", "D:\\newfile2.txt", 1)
};
try {
boolean dataAvailable = true;
int secondCount = 0;
while (dataAvailable) {
dataAvailable = false;
for (FileCopyDto d : files) {
d.write(secondCount);
dataAvailable = dataAvailable || d.isDataAvailable();
}
secondCount++;
Thread.sleep(1000);
}
for (FileCopyDto d : files) {
d.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
static class FileCopyDto {
String sourceFileName;
String destinationFileName;
int timeInSeconds;
BufferedReader br = null;
PrintWriter pw = null;
String nextLine;
public FileCopyDto(final String sourceFileName,
final String destinationFileName,
final int timeInSeconds) {
this.sourceFileName = sourceFileName;
this.destinationFileName = destinationFileName;
this.timeInSeconds = timeInSeconds;
}
public void open() throws IOException {
br = new BufferedReader(new FileReader(sourceFileName));
pw = new PrintWriter(new FileWriter(destinationFileName));
}
public boolean isDataAvailable() throws IOException {
if (br == null) {
open();
}
return (nextLine == null) || ((nextLine = br.readLine()) != null);
}
public void write(final int secondCount) {
if (nextLine != null && secondCount % timeInSeconds == 0) {
pw.println(nextLine);
pw.flush();
nextLine = null;
}
}
public void close() throws IOException {
br.close();
pw.close();
br = null;
}
}
source to share