I am writing a program in Java that requires me to compare the data in 2 files. I have to check each line from file 1 against each line of file 2 and if I find a match write them to a third file. After I read to the end of file 2, how do I reset the pointer to the beginning of the file?
public class FiFo {
public static void main(String[] args)
{
FileReader file1=new FileReader("d:\\testfiles\\FILE1.txt");
FileReader file2=new FileReader("d:\\testfiles\\FILE2.txt");
try{
String s1,s2;
while((s1=file1.data.readLine())!=null){
System.out.println("s1: "+s1);
while((s2=file2.data.readLine())!=null){
System.out.println("s2: "+s2);
}
}
file1.closeFile();
file2.closeFile();
}catch (IOException e) {
e.printStackTrace();
}
}
}
class FileReader {
BufferedReader data;
DataInputStream in;
public FileReader(String fileName)
{
try{
FileInputStream fstream = new FileInputStream(fileName);
data = new BufferedReader(new InputStreamReader(fstream));
}
catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile()
{
try{
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
fseek(fptr, 0, SEEK_SET); to reset the pointer to the start of the file. You cannot do that for stdin . If you need to be able to reset the pointer, pass the file as an argument to the program and use fopen to open the file and read its contents.
If you want to reset the pointer to the beginning of the file, you need to call the Seek() method on the file.
C library function - rewind() The C library function void rewind(FILE *stream) sets the file position to the beginning of the file of the given stream.
fseek() is used to move file pointer associated with a given file to a specific position. position defines the point with respect to which the file pointer needs to be moved. It has three values: SEEK_END : It denotes end of the file.
I believe RandomAccessFile
is what you need. It contains: RandomAccessFile#seek
and RandomAccessFile#getFilePointer
.
rewind()
is seek(0)
I think the best thing to do would be to put each line from file 1 into a HashMap
; then you could check each line of file 2 for membership in your HashMap
rather than reading through the entire file once for each line of file 1.
But to answer your question of how to go back to the beginning of the file, the easiest thing to do is to open another InputStream
/Reader
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With