java - 写入文件中的特定行,不带任何数据格式

标签 java

我想做的是,当用户想要编辑他的个人资料,然后按保存更改时,我想从所有 JTextField 获取文本并写入该特定行的文件中。然而经过3天的尝试却没有运气。我已经查看了这里有关读取和写入文件的所有帖子,但没有任何运气,所有方法都在下面,我将解释它们

public void save() throws IOException{
    String changes = name.getText() + "" + dob.getText() + "" 
            + "" + address.getText() + "" + town.getText() 
            + "" + number.getText();
    String whichLine = this.staff_no.getText();
    this.name.setEditable(false);
    this.dob.setEditable(false);
    this.address.setEditable(false);
    this.town.setEditable(false);
    this.number.setEditable(false);
    users.saveChanges(changes,whichLine);
}

这里我创建一个字符串,其中包含 JTextFields 中的所有文本,将它们设置回 false 并调用 saveChanges 方法(假设“替换”这个新字符串的方法)

public int getIndex(String staffno){
    for(User user : allUsers){
        if(user.getStaff_No().contains(staffno)){
            this.index = allUsers.indexOf(staffno);
            break;
        }
    }
    return this.index;
}

public void saveChanges(String changes, String whichLine) throws IOException{
    try {
        int count = 0;
        FileWriter writer = new FileWriter("records.txt", true);
        bw = new BufferedWriter(writer);
        while(scan.hasNext()){
            count++;
            if(count == getIndex(whichLine)){
                bw.write(changes);
                bw.newLine();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        if(bw != null){
            bw.close();
            reader.close();
        }
    }
}

现在我在这里获取用户的 Staffno 并通过我的用户 ArrayLists 运行它以查找其索引(假设为 0)。然后我循环遍历之前打开的扫描仪并尝试找到我可以查找的行覆盖该行。但是,我遇到了异常错误,例如 Stream closeed 或 NoSuchAnElementException 或根本没有错误,但不写入我的行或保存它。

这是我打开文件的方法

public void open(){
    try {
        URL path = Users.class.getResource("records.txt");
        File f = new File(path.getFile());
        reader = new BufferedReader(new FileReader(f));
        scan = new Scanner(reader);
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
    }
}

我不关闭扫描仪的原因是因为我会继续使用它来做其他事情

我意识到这是一个特定的场景,而不是一个简单的读/写场景,因此非常感谢任何帮助。

最佳答案

您想要执行的操作(覆盖文件中间的数据)只有在写入与要替换的字节数完全相同的情况下才能完成。也就是说,您不能用不同的行覆盖文件中的一行,除非它们的字节数完全相同(不一定是相同的字符数,具体取决于字符编码)。

您还保持扫描仪打开,以查找您正在积极写入的文件,该文件只是询问与缓冲相关的问题。

解决问题的绝对最简单的方法是按照coolguy的建议进行操作,将所有行读入内存,根据需要替换或添加行,然后将其全部写回。

但是,如果您不能或不想将整个文件缓存在内存中,您可以逐行读取文件,然后在更改相关行后将它们写回另一个文件,最后用新文件替换旧文件。

public static void writeChanges(String changes, int whichLine) throws IOException {
    // The files we're working with
    final File database = new File("database.txt");
    final File newDatabase = new File("database.new.txt");
    try(BufferedReader reader = new Bufferedreader(
            new InputStreamReader(new FileInputStream(database)));
            PrintWriter writer = new PrintWriter(newDatabase)) {
        int line = 0;
        String line;
        // Keep reading lines from the source file until we've read them all
        while((line = reader.readLine()) != null) {
            if(line == whichLine) {
                // Write the modified line
                writer.println(changes);
            } else {
                // Write the original line
                writer.println(line);
            }
            line++;
        }
    }
    // Replace the old database with the new
    Files.move(newDatabase.toPath(), database.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

关于java - 写入文件中的特定行,不带任何数据格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525203/

相关文章:

Java 字符串拆分为非字母字符

java - 启动 Activity 后调用方法

java - Maven Embedder - 运行 hibernate3 :hbm2java programmatically

java - 如何在java中比较两个 double 到最接近的百位数字

java - 为什么我无法使用我的对象的副本从该映射中 get() ?

java - Spring Boot 桌面独立应用程序中的 Apache Shiro

java - Activity <Activity name> 已泄漏最初在此处添加的窗口 DecorView@59feb10[activity]

java - 理解Java中的Set接口(interface)

java - 带内部 ui 的 Primefaces 数据表 :repeat

Java-如何检测环境