I'm pretty new to Java and decided to write a voting app and make use of jdbc and file handling. I seem have problems bringing the file pointer back to the starting of the file and upon using mark and reset it returns an error called "Mark Invalid" even though it returns markSupported as true. The following is a snippet of my code.
import java.sql.*;
import java.util.*;
import java.io.*;
public class Voting_App {
static Connection con;
static Statement crsr;
static BufferedReader br;
static Writer fw;
static File f;
static FileInputStream fstream;
static {
try {
fw= new FileWriter("posts.txt",true);
fstream = new FileInputStream("posts.txt");
br= new BufferedReader(new InputStreamReader(fstream));
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vote","root","root");
crsr= con.createStatement();
f= new File("posts.txt");
}
catch (SQLException e) {
e.printStackTrace();
}
catch (IOException i) {
i.printStackTrace();
}
}
static void disp_post() throws IOException {
br.mark(0);
String line;
int i=1;
if (f.length()!=0) {
while ((line=br.readLine())!=null) {
System.out.println(i+"."+line);
i++;
}
br.reset();
}
else {
System.out.println("There no posts currently");
}
}
This is the link to RandomAccessFile
Here to reset the file pointer you can simply use
seek(0)
in your code.
also if you want you can get current pointer location using
getFilePointer()
.