【发布时间】:2020-07-30 20:26:43
【问题描述】:
大家好,我是 java 新手,决定编写一个投票应用程序并使用 jdbc 和文件处理。 在使用 mark 和 时,我似乎无法将文件指针返回到文件的 开始 >reset 它返回一个名为“Mark Invalid”的错误,即使它返回 markSupported 为 true。以下是我的代码的sn-p。
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");
}
}
【问题讨论】:
-
如果还有其他我没有使用的好的编码实践,请指出。谢谢
-
为什么您的 Voting_App 中的所有内容都是静态的?我会使用骆驼案例来上课,所以请改用 VotingApp,就像您班级中的所有其他班级一样
-
你的缓冲区是空的,你用
mark(0)标记什么,不需要写if (f.length()!=0) {如果找不到文件会抛出NPEi的目的是什么?为什么所有closeable类都是静态的? -
@RAZ_Muh_Taz 我没有使用任何其他 java 文件或类,所以当我可以将所有内容保持为静态进行编写时,我没有找到创建对象的理由
-
@emotionlessbananas 怎么是空的?当我第一次调用该函数时它打印所有帖子时
标签: java file-handling