Re: Read a file multiple times
Federico wrote:
I, I've this code:
public class Main {
public static void main(String[] args) {
try {
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
FileReader input = new FileReader("in1.txt");
BufferedReader bufRead = new BufferedReader(input);
FileReader input2 = new FileReader("in2.txt");
BufferedReader bufRead2 = new BufferedReader(input2);
String line;
String line2;
line = bufRead.readLine();
line2 = bufRead2.readLine();
bufRead2.mark(7000000);
while (line != null) {
while(line2 != null) {
out.write(line + line2 + "\n");
line2 = bufRead2.readLine();
}
line = bufRead.readLine();
bufRead2.reset();
}
bufRead.close();
bufRead2.close();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Basically I want to read the file in1 and for each string founded,
combine it with all the in2 strings and write all in out:
For example:
in1.txt:
aaa
bbb
ccc
ddd
in2.txt:
eee
fff
ggg
hhh
iii
out.txt:
aaaeee
aaafff
aaaggg
aaahhh
aaaiii
bbbeee
bbbfff
...
dddiii
This will implement that for each line in in1.txt the bufferedreader
of in2.txt will be reset.
Obviusly this work onli for the first string of in1.txt.
Hi read the documentation for mark() and reset() but I can't solve
nothing with these methods.
I've to use vectors?
Maybe is better to use fileinputstream?
The choice depends on the file size, relative to the available memory.
The simplest solution is going to be to read one of the files into an
in-memory data structure, such as an ArrayList. Once you have done that,
you can read the other file a line at a time and output all pairs for
that line.
The fact that outputting all pairs seems reasonable to you suggests that
at least one of the files is reasonably small. For example, if the
smaller file contains a million lines, the list of pairs has at least
10**12 elements.
However, if neither file fits in memory, you are going to have to open
one of them as a RandomAccessFile. For each line of the other file, you
need to seek(0) in the RandomAccessFile and use readLine to advance
through it a line at a time.
Patricia