Reputation: 1167
I need to copy a line from a file to another depending on condition this is my code
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String args[]) throws IOException {
File source = \\
File fileToCopyFrom \\
File target :\\
if (!target.exists()) {
target.createNewFile();
}
PrintStream fstream =new PrintStream(target);
BufferedReader brSource = new BufferedReader(new FileReader(source));
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
String lineSource;
String lineToCopy;
while((lineSource = brSource.readLine()) != null) {
while ((lineToCopy=brFileToCopyFrom.readLine())!=null) {
if (lineToCopy.contains(lineSource.substring(lineSource.indexOf("_")+1, lineSource.indexOf(".")-1)))
fstream.println(lineToCopy);
}
}
}}
but it copy only the first line where is the error?
Upvotes: 1
Views: 5421
Reputation: 8640
you create your stream, you read all enntries from your stream, for first line, but when you want to do this for second line brFileToCopyFrom is empty (you already took everything from it when you were checking your first line.
so what you could do is move creating your brFileToCopyFrom
to the loop,
while((lineSource = brSource.readLine()) != null) {
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
...
that should works
Upvotes: 0
Reputation: 697
Only the first is copied because in the second iteration of the first while
the brFileToCopyFrom
is reached the end of file.
You need to open the BufferedReader brFileToCopy
inside the first while
(example 1) or use a mark/reset
feature (example 2).
Example 1:
while ((lineSource = brSource.readLine()) != null) {
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
...
}
}
}
Example 2:
brFileToCopyFrom.mark(1024); // number of characters to be read while preserving the mark
while ((lineSource = brSource.readLine()) != null) {
brFileToCopyFrom.reset();
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
...
}
}
}
Upvotes: 1
Reputation: 5496
I suggest to use commons-io.jar
. In this FileUtils
class lot of methods to do File
operation like copy, move and remove.
EDIT
try with below if conndition which contains break
.
while ((lineSource = brSource.readLine()) != null) {
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
if (lineToCopy.contains(lineSource.substring(
lineSource.indexOf("_") + 1,
lineSource.indexOf(".") - 1))) {
fstream.println(lineToCopy);
break;
}
}
}
Upvotes: 1