【问题标题】:Resetting the file pointer in JAVA file handling在 JAVA 文件处理中重置文件指针
【发布时间】:2020-07-30 20:26:43
【问题描述】:

大家好,我是 java 新手,决定编写一个投票应用程序并使用 jdbc 和文件处理。 在使用 ma​​rk 时,我似乎无法将文件指针返回到文件的 开始 >reset 它返回一个名为“Mark Invalid”的错误,即使它返回 ma​​rkSupported 为 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


【解决方案1】:

This is the link to RandomAccessFile

在这里重置文件指针,您可以简单地使用 seek(0) 在你的代码中。 如果您愿意,也可以使用获取当前指针位置 getFilePointer().

【讨论】:

  • 如果可能,请更正格式。如果格式不对任何人表示抱歉,我已尽力使用格式。
  • 啊,是的,这其实和 Python 的文件处理很相似,我试试看,尽快告诉你
  • 是的,请尝试,我之前使用过,所以我只是建议你这样做。
  • 非常感谢您提出这个解决方案,现在我可以安然入睡了 XD
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 2022-01-15
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2023-03-11
  • 2014-06-23
  • 1970-01-01
相关资源
最近更新 更多