英文:
Resetting the file pointer in JAVA file handling
问题
Hi All,我对Java相当新,并决定编写一个投票应用程序并利用JDBC和文件处理。我似乎在将文件指针返回到文件的起始位置时遇到了问题,使用mark和reset时返回了一个名为"Mark Invalid"的错误,尽管markSupported返回为true。以下是我的代码片段:
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");
}
}
}
请注意,代码中的注释和字符串已被保留为英文,以确保代码的正确性。
英文:
Hi All 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");
}
}
答案1
得分: 1
在这里,要重置文件指针,您只需在您的代码中使用
seek(0)
同时,如果您想要,您可以获取当前指针位置使用
getFilePointer()
.
英文:
This is the link to RandomAccessFile
Here to reset the file pointer you can simply use
<code>seek(0)</code>
in your code.
also if you want you can get current pointer location using
<code>getFilePointer()</code>.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论