0

当我从文本文件中删除一行,将其添加到临时文本文件中,然后用原始文件替换临时文件时,扫描仪没有加载正确的文本。它正在从原始文件加载内容,而不是更新文件。我希望它使用新内容加载更新的文件。

try
{
    File inputFile = new File("department.txt");
    File tempFile = new File("departmentTemp.txt");

    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

    String lineToRemove = departResIDField.getText();
    String currentLine;

    while((currentLine = reader.readLine()) != null) 
    {
         String trimmedLine = currentLine.trim();
         if(trimmedLine.startsWith(lineToRemove)) continue;
         writer.write(currentLine + System.getProperty("line.separator"));
    }

    writer.close(); 
    reader.close(); 
    inputFile.delete();
    tempFile.renameTo(inputFile);

    fWriter = new FileWriter(inputFile.getAbsoluteFile(), true);
    printOut = new PrintWriter(fWriter);
    writer = new BufferedWriter(fWriter);
    writer.write(departResIDField.getText() + "\t" + 
    departResNameField.getText() + "\r\n");
    writer.close();

    int result = Integer.parseInt(departResIDField.getText());
    depart.add(new Department(result, departResNameField.getText()));

    insResDepartModel.addElement(departResNameField.getText());

    depart.remove();

    //This is where I am having problem with the code
    //The scanner is scanning old data not the updated data             
    Scanner scan = new Scanner(inputFile);

    while(scan.hasNext())
    {
        depart.add(new Department(scan.nextInt(), scan.next()));
    }
    scan.close();

    for(int i = 0; i < depart.getSize(); i++)
    {
        Department d1 = depart.get(i);
        System.out.println(d1.departID + d1.departName);
    }

    menuLayout.show(cardLayout, "15");
    departResIDField.setText(null);
    departResNameField.setText(null);
    departUpdateButton.setVisible(false);
    departCancelButton.setVisible(false);
} catch (IOException f) 
    {
        f.printStackTrace();
    }

输出:1 生物 2 化学 4 统计 5 物理 3 数学

预期产出:1 生物学 2 化学 4 统计学 5 物理学 3 微积分

代码删除“3 Math”并添加“3 Calculus

4

2 回答 2

0

据我了解,您想将包含“3 Math”的行替换为“3 Calculus”。如果是这种情况,您可以执行以下操作:

    Path wiki_path = Paths.get("data/sample.txt");
    Charset charset = Charset.forName("UTF-8");

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      List<String> lines = Files.readAllLines(wiki_path, charset);
      int targetToReplaceIndex = -1;

      // You can modify this part to match your logic
      for (int i = 0; i < lines.size(); i++) {
          if (lines.get(i).startsWith("3 Math")) {
              targetToReplaceIndex = i;
              break;
          }
      }
      lines.set(targetToReplaceIndex, "3 Calculus");

      File temp = File.createTempFile("temp", ".tmp");
      temp.deleteOnExit();

      BufferedWriter out = new BufferedWriter(new FileWriter(temp));

      out.write(convertListToContent(lines));
      out.close();

      File orig = new File("data/sample.txt");

      fis = new FileInputStream(temp);
      fos = new FileOutputStream(orig);

      FileChannel src = fis.getChannel();
      FileChannel dest = fos.getChannel();
      dest.transferFrom(src, 0, src.size());

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
        try {
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

使用 Java 8将字符串列表转换为单个字符串的方法String非常简单:

private static String convertListToContent(List<String> lines) {
    StringBuilder contentBuilder = new StringBuilder();

    lines.forEach(l -> contentBuilder.append(l).append("\n"));

    return contentBuilder.toString();
}

希望能帮助到你。

于 2019-04-19T01:32:34.280 回答
0

当然有办法。LinkedList但是如果您只想保存主题,我建议您在文本文件中使用 , 之类的内容进行保存,并尝试只读取和写入一个File. 例如,您可以保存复杂的数据结构ObjectOutputStreamLinkedListjava实用程序有一个名为replace修改某些索引的指令。所以如果你想修改File你加载LinkedList保存的然后你修改列表并将其保存在同一个文件中。

于 2019-04-19T01:30:52.640 回答